美文网首页
Fortran 状态模式

Fortran 状态模式

作者: zoziha | 来源:发表于2020-09-27 18:22 被阅读0次

    为了增强计算机程序的健壮性,关于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
    

    相关文章

      网友评论

          本文标题:Fortran 状态模式

          本文链接:https://www.haomeiwen.com/subject/bfzkuktx.html