zoukankan      html  css  js  c++  java
  • 一天一个设计模式(18)——状态模式

    状态模式 

    当状态改变时,类的行为也发生改变。

    状态模式是以面向对象的方式实现状态机的行为设计模式。对于状态模式,通过将每个单独状态实现为派生类的状态模式接口, 来实现一个状态机,并通过调用模式超类的方法来实现状态转换。状态模式可以被解释为一种策略模式,它能够通过调用模式接口定义的方法来切换当前策略。

    实例

    <?php
    interface WritingState{
        public function write(string $words);
    }
    
    class UpperState implements WritingState{
        public function write(string $words){
            echo strtoupper($words);
        }
    }
    
    class LowerState implements WritingState{
        public function write(string $words){
            echo strtolower($words);
        }
    }
    
    class DefaultState implements WritingState{
        public function write(string $words){
            echo $words;
        }
    }
    
    class Editor{
        private $state;
        public function __construct(WritingState $state){
            $this->state=$state;
        }
    
        public function setState($state){
            $this->state=$state;
        }
    
        public function type(string $words){
            $this->state->write($words);
        }
    }
    
    $state=new DefaultState();
    $editor=new Editor($state);
    $editor->type("First Type");
    
    $editor->setState(new UpperState());
    $editor->type("Second Type");
    
    $editor->setState(new LowerState());
    $editor->type("Third Type");
    状态模式实例

    本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/7453138.html

  • 相关阅读:
    10分钟入门spark
    10分钟入门kubernetes(上)
    深入浅出Hadoop之mapreduce
    深入浅出Hadoop之HDFS
    闲聊cassandra
    深入浅出zookeeper
    Asp.net日期字符串格式化显示
    C#里面比较时间大小三种方法
    (ASP.net)利用Application对象制作简单聊天室
    Response.ContentType 详细列表
  • 原文地址:https://www.cnblogs.com/Bin-x/p/7453138.html
Copyright © 2011-2022 走看看