State模式(状态模式)消除烦琐的if..else语句

State模式的定义: 不同的状态,不同的行为;或者说,每个状态有着相应的行为.
    何时使用 :State模式在实际使用中比较多,适合"状态的切换".因为我们经常会使用If elseif else 进行状态切换, 如果针对状态的这样判断切换反复出现,我们就要联想到是否可以采取State模式了.
    通常的模式下我们需要根据状态来来判断动作都是使用一连串的 if...else 语句,例如:

enum PaperColor{
    WHITE,BLACK,BLUE,RED
}

class MyPaper
{
    PaperColor paperColor;

    public MyPaper(PaperColor color){
        this.paperColor=color;
    }

    public PaperColor getMyPaperColor(){
        return this.paperColor;
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        MyPaper myPaper = new MyPaper(PaperColor.WHITE);

        if(myPaper.getMyPaperColor()==PaperColor.WHITE){
            System.out.println("You need a black pen");
        }else if(myPaper.getMyPaperColor()==PaperColor.BLACK){
            System.out.println("You need a white pen");
        }else if(myPaper.getMyPaperColor()==PaperColor.BLUE){
            System.out.println("You need a red pen");
        }else if(myPaper.getMyPaperColor()==PaperColor.RED){
            System.out.println("You need a blue pen");
        }
    }
}

运行结果:

You need a black pen

    白色的纸张需要黑色的笔,黑色的纸张需要白色的笔,蓝色的纸张需要红色的笔,红色的纸张需要蓝色的笔.....
    由上面程序看来,只要有多少种纸就需要多少个 else if 如果以后存在别的颜色的纸就必须在枚举里面加类型同时继续的添加 else if 然后再重新编译,显然这样的代码对日后扩展非常不利.这样的问题我们可以用State模式得到解决.

interface PaperColor{
    public void getPenColor();
}

class White implements PaperColor
{
    public void getPenColor(){
        System.out.print("You need a black pen");
    }
}

class Black implements PaperColor
{
    public void getPenColor(){
        System.out.print("You need a white pen");
    }
}

class Blue implements PaperColor
{
    public void getPenColor(){
        System.out.print("You need a red pen");
    }
}

class Red implements PaperColor
{
    public void getPenColor(){
        System.out.print("You need a blue pen");
    }
}

class MyPaper
{
    PaperColor paperColor;

    public MyPaper(PaperColor color){
        this.paperColor=color;
    }

    public PaperColor getMyPaperColor(){
        return this.paperColor;
    }

    public void choicePen(){
        this.paperColor.getPenColor();
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        PaperColor color = new Blue();
        MyPaper myPaper = new MyPaper(color);
        myPaper.choicePen();
    }
}

运行结果:
You need a red pen

    State模式不但使得程序容易扩展同时也消除了烦琐的if...else语句.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值