美文网首页
goF23设计模式~思想学习笔记(三)

goF23设计模式~思想学习笔记(三)

作者: 朱允见 | 来源:发表于2022-07-08 09:53 被阅读0次

goF23设计模式~思想学习笔记(一)
goF23设计模式~思想学习笔记(二)

行为型模式

  1. 模板方法模式(Template Method Pattern): 定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。Template Method使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
    image.png
abstract public class SoyMilk {
    void make(){
        select();
        add();
        soak();
        beat();
    }

    void select(){
        System.out.println("挑选尚好大豆");
    }
    abstract void add();
    void soak(){
        System.out.println("浸泡");
    }
    void beat(){
        System.out.println("打碎");
    }
}
public class BlackSoyMilk extends SoyMilk {

    @Override
    void add() {
        System.out.println("添加黑豆");
    }
}
public class PeanutSoyMilk extends SoyMilk {

    @Override
    void add() {
        System.out.println("添加花生");
    }
}

public class Test {
    public static void main(String[] args) {
        SoyMilk soyMilk = new BlackSoyMilk();
        soyMilk.make();

        System.out.println("----------");
        soyMilk = new PeanutSoyMilk();
        soyMilk.make();

    }
}

  • 1.2 模板钩子
//模板钩子
abstract public class SoyMilk {
    void make(){
        select();
        if(hasCondiments()){
            add();
        }

        soak();
        beat();
    }

    void select(){
        System.out.println("挑选尚好大豆");
    }
    abstract void add();
    void soak(){
        System.out.println("浸泡");
    }
    void beat(){
        System.out.println("打碎");
    }
    boolean hasCondiments() {
        return true;
    }
}
public class PureSoyMilk extends SoyMilk {
    @Override
    void add() {}

    @Override
    boolean hasCondiments() {
        return false;
    }
}

  1. 责任链模式(Chain of Responsibility Pattern): 为解除请求的发送者和接收者之间耦合,而使多个对象都有机会处理这个请求。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它。
    image.png
abstract public class Approver {
    Approver approver;
    String name;

    public Approver(String name) {
        this.name = name;
    }

    abstract void processRequest(PurchaseRequest purchaseRequest);

    public void setApprover(Approver approver) {
        this.approver = approver;
    }
}

public class PurchaseRequest {
    double price;
    public PurchaseRequest(double price) {
        this.price = price;
    }
}

public class DepartmentApprover extends Approver {
    public DepartmentApprover(String name) {
        super(name);
    }

    @Override
    void processRequest(PurchaseRequest purchaseRequest) {
        if(purchaseRequest.price < 1000){
            System.out.println(this.name + "处理");
        }else {
            approver.processRequest(purchaseRequest);
        }
    }
}

public class CollegeApprover extends Approver {

    public CollegeApprover(String name) {
        super(name);
    }

    @Override
    void processRequest(PurchaseRequest purchaseRequest) {
        if(purchaseRequest.price < 2000){
            System.out.println(this.name + "处理");
        }else {
            approver.processRequest(purchaseRequest);
        }
    }
}

public class ViceSchoolMasterApprover extends Approver {

    public ViceSchoolMasterApprover(String name) {
        super(name);
    }

    @Override
    void processRequest(PurchaseRequest purchaseRequest) {
        if(purchaseRequest.price < 3000){
            System.out.println(this.name + "处理");
        }else {
            approver.processRequest(purchaseRequest);
        }
    }
}

public class SchoolMasterApprover extends Approver {

    public SchoolMasterApprover(String name) {
        super(name);
    }

    @Override
    void processRequest(PurchaseRequest purchaseRequest) {
        if(purchaseRequest.price >= 3000){
            System.out.println(this.name + "处理");
        }else {
            approver.processRequest(purchaseRequest);
        }
    }
}

public class Test {
    public static void main(String[] args) {
        PurchaseRequest purchaseRequest = new PurchaseRequest(4000);
        DepartmentApprover departmentApprover = new DepartmentApprover("部门");
        CollegeApprover collegeApprover = new CollegeApprover("学院");
        ViceSchoolMasterApprover viceSchoolMasterApprover = new ViceSchoolMasterApprover("副校");
        SchoolMasterApprover schoolMasterApprover = new SchoolMasterApprover("校长");

        departmentApprover.setApprover(collegeApprover);
        collegeApprover.setApprover(viceSchoolMasterApprover);
        viceSchoolMasterApprover.setApprover(schoolMasterApprover);
        schoolMasterApprover.setApprover(departmentApprover);

        departmentApprover.processRequest(purchaseRequest);

    }
}
  1. 观察者模式(Observer Pattern): 定义对象间的一种一对多的依赖关系,以便当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并自动刷新。
    image.png
public interface Subject {
    void register(Observer observer);
    void remove(Observer observer);
    void notifyObservers();
}

public class WeatherData implements Subject {
    List<Observer> observerList = new ArrayList<Observer>();
    private float temperature;

    public WeatherData(float temperature) {
        this.temperature = temperature;
    }

    //温度变化通知订阅者
    public void setTemperature(float temperature) {
        this.temperature = temperature;
        notifyObservers();
    }

    @Override
    public void register(Observer observer) {
        observerList.add(observer);
    }

    @Override
    public void remove(Observer observer) {
        observerList.remove(observer);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer:observerList) {
            observer.update(temperature);
        }
    }
}

public interface Observer {
    void update(float temperature);
}

public class Sina implements Observer {
    @Override
    public void update(float temperature) {
        System.out.println("sina ==" + temperature);
    }
}

public class Test {
    public static void main(String[] args) {
        WeatherData weatherData = new WeatherData(28);
        Sina sina = new Sina();
        weatherData.register(sina);

        weatherData.setTemperature(20);
    }
}
  1. 迭代器模式(Iterator Pattern): 提供一种方法顺序访问一个聚合对象中各个元素, 而又不需暴露该对象的内部表示。
    image.png
public interface Iterator<E> {
    boolean hasNext();
    E next();
}

public class ComputerCollegeIterator implements Iterator {
    List<Department> departmentList;
    int position = -1;

    public ComputerCollegeIterator(List<Department> departmentList) {
        this.departmentList = departmentList;
    }

    @Override
    public boolean hasNext() {
        return position < departmentList.size() - 1;
    }

    @Override
    public Object next() {
        position += 1;
        return departmentList.get(position);
    }
}

public class InfoCollegeIterator implements Iterator {
    List<Department> departmentList = new ArrayList<Department>();
    int position = -1;

    public InfoCollegeIterator(List<Department> departmentList) {
        this.departmentList = departmentList;
    }

    @Override
    public boolean hasNext() {
        return position < departmentList.size() - 1;
    }

    @Override
    public Object next() {
        position += 1;
        return departmentList.get(position);
    }    
}
public interface College {
    public String getName();
    public void addDepartment(String name,String desc);
    Iterator createIterator();
}

public class ComputerCollege implements College {
    List<Department> departmentList = new ArrayList<Department>();

    ComputerCollege(){
        addDepartment("Java专业","Java专业desc");
        addDepartment("Php专业","Php专业desc");
        addDepartment("iOS专业","iOS专业desc");
    }

    @Override
    public String getName() {
        return "计算机学院";
    }

    @Override
    public void addDepartment(String name, String desc) {
        departmentList.add(new Department(name,desc));
    }

    @Override
    public Iterator createIterator() {
        return new ComputerCollegeIterator(departmentList);
    }
}

public class ComputerCollege implements College {
    List<Department> departmentList = new ArrayList<Department>();

    ComputerCollege(){
        addDepartment("Java专业","Java专业desc");
        addDepartment("Php专业","Php专业desc");
        addDepartment("iOS专业","iOS专业desc");
    }

    @Override
    public String getName() {
        return "计算机学院";
    }

    @Override
    public void addDepartment(String name, String desc) {
        departmentList.add(new Department(name,desc));
    }

    @Override
    public Iterator createIterator() {
        return new ComputerCollegeIterator(departmentList);
    }
}

public class InfoCollege implements College {

    List<Department> departmentList = new ArrayList<Department>();

    InfoCollege(){
        addDepartment("信息 Java专业","信息 Java专业desc");
        addDepartment("信息 Php专业","信息 Php专业desc");
        addDepartment("信息 iOS专业","信息 iOS专业desc");
    }

    @Override
    public String getName() {
        return "信息学院";
    }

    @Override
    public void addDepartment(String name, String desc) {
        departmentList.add(new Department(name,desc));
    }

    @Override
    public Iterator createIterator() {
        return new InfoCollegeIterator(departmentList);
    }
}

public class Department {
    private String name;
    private String desc;

    public Department(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }
}

public class OutputImp {
    List<College> collegeList ;

    public OutputImp(List<College> collegeList) {
        this.collegeList = collegeList;
    }

    public void printCollege(){
        for(College college:collegeList){
            System.out.println("-----"+ college.getName() +"----");
            printDepartment(college.createIterator());
        }
    }
    //输出学院的系
    public void printDepartment(Iterator iterator){

        while (iterator.hasNext()){
            Department department = (Department) iterator.next();
            System.out.println(department.getName());
        }
    }
}

public class Test {
    public static void main(String[] args) {

        ComputerCollege computerCollege = new ComputerCollege();

        InfoCollege infoCollege = new InfoCollege();

        List<College> collegeList = new ArrayList<College>();
        collegeList.add(computerCollege);
        collegeList.add(infoCollege);

        OutputImp outputImp = new OutputImp(collegeList);
        outputImp.printCollege();

  /*
-----计算机学院----
Java专业
Php专业
iOS专业
-----信息学院----
信息 Java专业
信息 Php专业
信息 iOS专业
*/
    }
}
  1. 命令模式(Command Pattern): 将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可取消的操作。
    image.png
public interface Command {
    void execute();
    void undo();
}

public class NoCommand implements Command {
    @Override
    public void execute() {}

    @Override
    public void undo() {}
}

public class LightOnCommand implements Command {
    private LightReceiver receiver;

    public LightOnCommand(LightReceiver receiver) {
        this.receiver = receiver;
    }

    @Override
    public void execute() {
        receiver.on();
    }

    @Override
    public void undo() {
        receiver.off();
    }
}

public class LightOffCommand implements Command {

    private LightReceiver receiver;

    public LightOffCommand(LightReceiver receiver) {
        this.receiver = receiver;
    }

    @Override
    public void execute() {
        receiver.off();
    }

    @Override
    public void undo() {
        receiver.on();
    }
}

public class LightReceiver {
    void on(){
        System.out.println("灯 开....");
    }
    void off(){
        System.out.println("灯 关....");
    }
}

public class RemoteController {
    List<Command> onCommandList = new ArrayList<Command>();
    List<Command> offCommandList = new ArrayList<Command>();
    Command lastCommand = new NoCommand();

    private static final int row = 5;

    RemoteController(){
        for(var i=0;i<row;i++){
            onCommandList.add(new NoCommand());
            offCommandList.add(new NoCommand());
        }
    }

    private boolean checkIndex(int row){
        return row >= 0 && row < RemoteController.row;
    }

    public void setCommand(int row,Command onCommand,Command offCommand) {
        if(checkIndex(row)){
            offCommandList.set(row, offCommand);
            onCommandList.set(row,onCommand);
        }
    }

    public void pressOn(int row){
        if(checkIndex(row)){
            lastCommand = onCommandList.get(row);
            lastCommand.execute();
        }
    }
    public void pressOff(int row){
        if(checkIndex(row)){
            lastCommand = offCommandList.get(row);
            lastCommand.execute();
        }
    }
    public void pressUndo(){
        lastCommand.undo();
    }

}

public class Test {
    public static void main(String[] args) {

        //遥控器
        RemoteController remoteController = new RemoteController();

        //灯
        LightReceiver lightReceiver = new LightReceiver();

        Command lightOffCommand = new LightOffCommand(lightReceiver);
        Command lightOnCommand = new LightOnCommand(lightReceiver);

        //设置化命令
        remoteController.setCommand(0,lightOnCommand,lightOffCommand);

        //开
        remoteController.pressOn(0);
        remoteController.pressUndo();

    }
}
  1. 备忘录模式(Memento Pattern): 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到保存的状态。
    image.png
public class GameRole {
    private int vit;
    private int def;


    public GameRole( int vit,int def) {
        this.def = def;
        this.vit = vit;
    }
    void setNewValue(int vit,int def){
        this.def = def;
        this.vit = vit;
    }

    Memento createMemento(){
        return  new Memento(vit,def);
    }
    void recover(Memento memento){
        vit = memento.getVit();
        def = memento.getDef();
    }

    @Override
    public String toString() {
        return "GameRole{" +
                "vit=" + vit +
                ", def=" + def +
                '}';
    }
}

//捕获者
public class CareTaker {
    private Memento memento;

    public Memento getMemento() {
        return memento;
    }

    public void setMemento(Memento memento) {
        this.memento = memento;
    }
}

public class Memento {
    private int vit;
    private int def;


    public Memento(int vit,int def) {
        this.def = def;
        this.vit = vit;
    }

    public int getDef() {
        return def;
    }

    public void setDef(int def) {
        this.def = def;
    }

    public int getVit() {
        return vit;
    }

    public void setVit(int vit) {
        this.vit = vit;
    }
}

public class Test {
    public static void main(String[] args) {
        
        //捕获者
        CareTaker careTaker = new CareTaker();

        //游戏角色 初始化满血
        GameRole gameRole = new GameRole(100,100);

        careTaker.setMemento(gameRole.createMemento());

        //中途血量减少
        gameRole.setNewValue(50,30);
        System.out.println(gameRole);

        //满血恢复
        gameRole.recover(careTaker.getMemento());
        System.out.println(gameRole);

    }
}

  1. 状态模式(State Pattern): 允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它所属的类。
    image.png
abstract public class State {
    Activity activity;

    public State(Activity activity) {
        this.activity = activity;
    }

    //扣积分
    void deduceMoney(){};
    //是否抽中
    boolean raffle(){
        return false;
    };
    //发放奖品
    void dispensePrize(){};
}

////无抽奖资格状态 -扣分改变成可抽奖状态
public class NoRaffleState extends State {
    
    public NoRaffleState(Activity activity) {
        super(activity);
    }

    @Override
    void deduceMoney() {
        System.out.println("扣除50积分");
        activity.setState(new CanRaffleState(activity));
    }

}

//可抽奖状态
public class CanRaffleState extends State {
    public CanRaffleState(Activity activity) {
        super(activity);
    }

    @Override
    boolean raffle() {
        System.out.println("正在抽奖");
        Random random = new Random();
        int num = random.nextInt(10);
        if(num==0){
            //抽中
            activity.setState(new DispenseState(activity));
            return true;
        }else  {
            //未中
            activity.setState(new NoRaffleState(activity));
            return false;
        }
    }
}

//发奖 状态
public class DispenseState extends State {
    
    public DispenseState(Activity activity) {
        super(activity);
    }

    @Override
    void dispensePrize() {
        if(activity.getPrizeCount()>0){
            System.out.println("恭喜你 成功领取奖品");
            activity.setState(new NoRaffleState(activity));
        }else {
            System.out.println("很遗憾 奖品没有了");
            activity.setState(new DispenseOutState(activity));
        }
    }
}

//不能发奖
public class DispenseOutState extends State {
    public DispenseOutState(Activity activity) {
        super(activity);
    }
}

public class Test {
    public static void main(String[] args) {
        Activity activity = new Activity(3);

        for(int i=0;i<100;i++){
            System.out.println(i);
            activity.deductMoney();
            activity.raffle();
        }
    }
}

  1. 解释器模式(Interpreter Pattern): 给定一个语言,定义它的文法的一种表示,并定义一个解释器, 该解释器使用该表示来解释语言中的句子。
    image.png
public interface Expression {
    //表达式 value  {a = 10,b=20}
    int interpreter(HashMap<String,Integer> map);
}

//变量解释器
public class VarExpression implements Expression {
    private String key;

    public VarExpression(String key) {
        this.key = key;
    }

    @Override
    //根据变量名称返回对应的值
    public int interpreter(HashMap<String, Integer> map) {
        return map.get(key);
    }
}

abstract public class SymbolExpression implements Expression {
    protected Expression left;
    protected Expression right;

    public SymbolExpression(Expression left, Expression right) {
        this.left = left;
        this.right = right;
    }

    @Override
    abstract public int interpreter(HashMap<String, Integer> map);
}

public class AddExpression extends SymbolExpression {

    public AddExpression(Expression left, Expression right) {
        super(left, right);
    }

    @Override
    public int interpreter(HashMap<String, Integer> map) {
        return super.left.interpreter(map) + super.right.interpreter(map);
    }
}

public class SubExpression extends SymbolExpression {

    public SubExpression(Expression left, Expression right) {
        super(left, right);
    }

    @Override
    public int interpreter(HashMap<String, Integer> map) {
        return super.left.interpreter(map) - super.right.interpreter(map);
    }
}

public class Calculator {
    private Expression expression;

    public Calculator(String expStr) {
        Stack<Expression> stack = new Stack<Expression>();
        char[] chars = expStr.toCharArray();

        Expression left = null;
        Expression right = null;

        for (int i=0;i<chars.length;i++){
            switch (chars[i]){
                case '+':
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(chars[++i]));
                    stack.push(new AddExpression(left,right));
                    break;
                case '-':
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(chars[++i]));
                    stack.push(new SubExpression(left,right));
                    break;
                default:
                    stack.push(new VarExpression(String.valueOf(chars[i])));
                    break;
            }
        }
        this.expression = stack.pop();
    }
    int run(HashMap<String,Integer> map){
        return this.expression.interpreter(map);
    }
}

public class Test {
    public static void main(String[] args) {
        Calculator calculator = new Calculator("a+b-c");

        HashMap hashMap = new HashMap();
        hashMap.put("a",10);
        hashMap.put("b",20);
        hashMap.put("c",4);
        int run = calculator.run(hashMap);
        System.out.println(run);
    }
}
  1. 访问者模式(Visitor Pattern): 表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
    image.png
public interface Action {
    void getManResult(Man man);
    void getWoManResult(Woman woman);
}

public class Success implements Action {
    @Override
    public void getManResult(Man man) {
        System.out.println("男人评价成功");
    }

    @Override
    public void getWoManResult(Woman woman) {
        System.out.println("女人评价成功");
    }
}

public class Fail implements Action {
    @Override
    public void getManResult(Man man) {
        System.out.println("男人评价失败");
    }

    @Override
    public void getWoManResult(Woman woman) {
        System.out.println("女人评价失败");
    }
    
}

public class ObjectStructure {
    List<Person> personList = new ArrayList<Person>();

    void attach(Person person){
        personList.add(person);
    }
    void detach(Person person){
        personList.remove(person);
    }
    void display(Action action){
        for (Person person: personList) {
            person.accept(action);
        }
    }

}

abstract public class Person {
    abstract void accept(Action action);
}
public class Man extends Person {
    @Override
    void accept(Action action) {
        action.getManResult(this);
    }
}
public class Woman extends Person {
    @Override
    void accept(Action action) {
        action.getWoManResult(this);
    }
}

public class Test {
    public static void main(String[] args) {
        ObjectStructure objectStructure = new ObjectStructure();
        objectStructure.attach(new Man());
        objectStructure.attach(new Woman());

        objectStructure.display(new Success());
        /* 输出---
            男人评价成功
            女人评价成功
        */
        objectStructure.display(new Fail());
        /* 输出---
           男人评价失败
           女人评价失败
        */
    }
}
  1. 中介者模式(Mediator Pattern): 用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
    image.png
public interface Mediator {
    void getMessage(int status,String name);
    void register(String name,Colleague colleague);
}

public class ConcreteMediator implements Mediator {
    Map<String,Colleague> map = new HashMap<String,Colleague>();
    Map<String,String> interMap = new HashMap<String,String>();


    @Override
    public void getMessage(int status, String name) {
        Colleague colleague = map.get(name);
        if(colleague instanceof Alarm){
            String key = interMap.get("TV");
            TV tv = (TV) map.get(key);

            if(status==1){
                tv.on();
            }else if(status==0){
                tv.off();
            }
        }
    }

    @Override
    public void register(String name, Colleague colleague) {
        map.put(name,colleague);
        if(colleague instanceof Alarm){
            interMap.put("Alarm", name);
        }else if(colleague instanceof TV){
            interMap.put("TV", name);
        }
    }
}

abstract public class Colleague {
    Mediator mediator;
    String name;

    public Colleague(Mediator mediator, String name) {
        this.mediator = mediator;
        this.name = name;
    }

    Mediator getMediator() {
        return mediator;
    }

    abstract void sendMessage(int status);

}


public class TV extends Colleague {


    public TV(Mediator mediator, String name) {
        super(mediator, name);
        mediator.register(name,this);
    }

    void sendTVMessage(int status){
        sendMessage(status);
    }

    void on(){
        System.out.println("TV 开机");
    }
    void off(){
        System.out.println("TV 关机");
    }

    @Override
    void sendMessage(int status) {
        this.mediator.getMessage(status,this.name);
    }
}

public class Alarm extends Colleague {

    public Alarm(Mediator mediator, String name) {
        super(mediator, name);
        mediator.register(name,this);
    }

    void sendAlarm(int status) {
        System.out.println("Alarm ===" + status);
        sendMessage(status);
    }

    @Override
    void sendMessage(int status) {
        this.getMediator().getMessage(status,this.name);
    }
    
}


public class Test {
    public static void main(String[] args) {

        //中介者模式
        ConcreteMediator concreteMediator = new ConcreteMediator();
        Alarm alarm = new Alarm(concreteMediator,"Alarm1");
        new TV(concreteMediator,"TV1");

        //闹钟 到了 开关电视
        alarm.sendAlarm(0);
    }
}
  1. 策略模式(Strategy Pattern): 定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法的变化可独立于使用它的客户。
    image.png

public interface FlyBehavior {
    String fly();
}
public class GoodFly implements FlyBehavior {
    @Override
    public String fly() {
        return "飞行很好";
    }
}
public class BadFly implements FlyBehavior {
    @Override
    public String fly() {
        return "飞行很差";
    }
}

public class NoFly implements FlyBehavior {
    @Override
    public String fly() {
        return "不会飞行";
    }
}
abstract public class Duck {
    String name;
    FlyBehavior flyBehavior;

    public Duck(String name, FlyBehavior flyBehavior) {
        this.name = name;
        this.flyBehavior = flyBehavior;
    }

    public void display() {
        String s = this.getClass() +
                "name='" + name + '\'' +
                "fly=" + flyBehavior.fly();
        System.out.println(s);
    }
}
public class WildDuck extends Duck {

    public WildDuck(String name) {
        super(name, new GoodFly());
    }
}

public class PekingDuck extends Duck {

    public PekingDuck(String name) {
        super(name, new BadFly());
    }
}

public class ToyDuck extends Duck{

    public ToyDuck(String name ) {
        super(name, new NoFly());
    }
}

public class Test {
    public static void main(String[] args) {
        Duck pekingDuck = new PekingDuck("北京鸭");
        pekingDuck.display();

        Duck wildDuck = new WildDuck("野鸭");
        wildDuck.display();

        Duck toyDuck = new ToyDuck("玩具鸭");
        toyDuck.display();
    }
}

相关文章

网友评论

      本文标题:goF23设计模式~思想学习笔记(三)

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