为了增强计算机程序的健壮性,关于Fortran的设计模式网上资料难以查找,于是借鉴go语言的状态模式,改编出了Fortran的状态模式。
module context
implicit none
type, public :: HungryState
logical :: State
contains
procedure :: HungryProcedure
procedure :: NoHungryProcedure
end type
type, public :: Person
type(HungryState) :: HungryState
contains
procedure :: Eat
procedure :: Work
end type
type, public :: Hungry
end type
type, public :: NoHungry
end type
contains
subroutine Eat(this)
class(Person) :: this
if (this % HungryState % state) then
write(6, "(A)") "Eatting.."
!!// 改变状态
call this % HungryState % NoHungryProcedure
else
write(6, "(A)") "Already baole!!"
end if
end subroutine
subroutine Work(this)
class(Person) :: this
if (this % HungryState % state) then
write(6, "(A)") "I am hungry, no work!!"
else
write(6, "(A)") "Ok, let us do work.."
call this % HungryState % HungryProcedure
end if
end subroutine
subroutine HungryProcedure(this)
class(HungryState) :: this
this % state = .true.
end subroutine
subroutine NoHungryProcedure(this)
class(HungryState) :: this
this % state = .false.
end subroutine
end module
program main
use context
implicit none
type(Person) :: p
call p % HungryState % NoHungryProcedure
call p % Eat
call p % Work
call p % Eat
call p % Eat
end program
网友评论