设计模式(一) 策略模式

概述

策略模式算是设计模式中比较好理解的,其实就是在运行期间动态的修改一个抽象类的具体实现,从而实现了每个具体类的不同的"策略"。

组成

—抽象策略角色: 策略类,通常由一个接口或者抽象类实现。

—具体策略角色:包装了相关的算法和行为。

—环境角色:持有一个策略类的引用,最终给客户端调用。

代码实现

//抽象策略角色

public interface Strategy{

     void attendClass();//上课

}

//具体策略角色

public class ChineseTeacher implements Strategy{

     private String name;

    public ChineseTeacher(String name){

        this.name=name;

    }

    @Override

    public void attendClass(){

        System.out.println(name + " 来上课了!");

    }

}

public class EnglishTeacher implements Strategy{

     private String name;

    public EnglishTeacher(String name){

        this.name=name;

    }

    @Override

    public void attendClass(){

        System.out.println(name + " 来上课了!");

    }

}

public class MathTeacher implements Strategy{

     private String name;

    public MathTeacher(String name){

        this.name=name;

    }

    @Override

    public void attendClass(){

        System.out.println(name + " 来上课了!");

    }

}

//环境角色

public class Context{

    private Strategy strategy;

    public Context(){}

    public void setContext(Strategy strategy){

        this.strategy=strategy;

    }

    public void contextInterface(){

        if(strategy==null){

            System.out.println("请选择老师");

            return;

        }

        strategy.attendClass();

    }

}

//测试类

public class Test{

    public static void main(String[] args){

        Context context=new Context();

        ChineseTeacher chineseTeacher=new ChineseTeacher("语文老师");

        EnglishTeacher englishTeacher=new EnglishTeacher("英语老师");

        MathTeacher mathTeacher=new MathTeacher("数学老师");

        context.setContext(chineseTeacher);

        context.contextInterface();

        context.setContext(englishTeacher);

        context.contextInterface();

        context.setContext(mathTeacher);

        context.contextInterface();

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值