Clicky

Fortran Wiki
Strategy Pattern (changes)

Skip the Navigation Links | Home Page | All Pages | Recently Revised | Authors | Feeds | Export |

Showing changes from revision #0 to #1: (追記) Added (追記ここまで) | (削除) Removed (削除ここまで) | (削除) Chan (削除ここまで)(追記) ged (追記ここまで)

Strategy Pattern

Strategy Pattern is a design pattern whereby the algorithm ("strategy") is selected at run-time, instead of embedding it as a type-bound procedure. Fortran 2003 introduces the concept of procedure pointers and abstract interfaces, which can be used to select the procedure at runtime (polymorphism).

Here is an example:

module m_strategy_pattern
implicit none
type :: Button
 character(len=20) :: label
 procedure(generic_function), pointer, nopass :: on_submit
contains
 procedure :: init
end type Button
abstract interface
 subroutine generic_function(numbers)
 integer, dimension(:), intent(in) :: numbers
 end subroutine
end interface
contains
 subroutine init(self, func, label)
 class(Button), intent(inout) :: self
 procedure(generic_function) :: func
 character(len=*) :: label
 self%on_submit => func !! Procedure pointer
 self%label = label
 end subroutine init
 subroutine summation(array)
 integer, dimension(:), intent(in) :: array
 integer :: total
 total = sum(array)
 write(*,*) total
 end subroutine summation
 subroutine join(array)
 integer, dimension(:), intent(in) :: array
 write(*,*) array !! Just write out the whole array
 end subroutine join
end module m_strategy_pattern
program test_strategy
use m_strategy_pattern
implicit none
 type(Button) :: button1, button2
 integer :: i
 call button1%init(summation, "Add them")
 call button2%init(join, "Join them")
 call button1%on_submit([(i, i=1,10)]) !! Array constructor syntax
 call button2%on_submit([(i, i=1,10)])
end program test_strategy
Created on June 20, 2010 11:08:36 by Satish (117.192.197.139) (1834 characters / 0.0 pages)
Edit | Views: Print | TeX | Source | Linked from: Design patterns, Design Patterns

AltStyle によって変換されたページ (->オリジナル) /