开发杂谈:关于程序设计原则和设计模式的那些事儿

程序设计原则是我们在程序设计开发过程中所尊循的一些基本准则,是程序设计总的指导思想,是我们在程序设计中永远所追求的目标。而设计模式是人们在长期的编程实践中所总结归纳出来的解决某些特定问题的通用的模板、方法和技巧。无论是设计原则也好,还是设计模式也罢,他们和语言无关,和具体的业务无关,具备广泛的适用性。

设计原则

最近一直打算写一篇关于程序设计原则和设计模式的文章,没有想到这事一拖尽然跨年了,今天已经是1月8号,这也是我2020年写的第一篇文章,也祝愿自己在新的一年里能心想事成,一帆风顺。

不知不觉自己坚持写文章已经有一年的时间了,发表了近100篇文章,有数据结构和算法的,也有架构设计和开源框架的,还有一部分是Android方面的,当然还有几篇是和技术无关的书法作品,但是关于程序设计原则和设计模式的文章一篇也没有,虽然在Android应用架构发展简史一文中有过一些简单介绍。

程序设计原则是我们在程序设计开发过程中所尊循的一些基本准则,是程序设计总的指导思想,是我们在程序设计中永远所追求的目标。而设计模式是人们在长期的编程实践中所总结归纳出来的解决某些特定问题的通用的模板、方法和技巧。无论是设计原则也好,还是设计模式也罢,他们和语言无关,和具体的业务无关,具备广泛的适用性。程序设计六大原则是软件开发中总的指导思想;而23种设计模式是这六大设计原则的具体实践,由于它不是工具,没有一个具体的度量标准,你完全可以有自己独到的见解和看法,你对它理解的有多么的深入,你就可以写出多么优秀的代码。

平时我们用的一些优秀的开源框架,研究它的源代码我们会发现,其中所体现出来的设计原则和设计模式真是无处不在。而我们日常开发过程中很多程序员只顾着具体的业务功能的实现,而没有尊循程序设计六大原则,没有使用好设计模式,使我们的软件在后期的维护开发过程中付出了巨大的成本,更谈不上程序的易维护性,复用性和可扩展性了。

学好设计模式需要有一定的项目编码经验,如果初学编程直接学设计模式它将是非常困难的,因为你没有任何实战开发,导致对这些设计原则和设计模式而无法理解,学到都是一些似是而非的东西。在实践中去学,在学中去实践,这样你才能理解它的主要精神思想。说句实话,我在这么多年的开发实践中形形色色的程序员也都遇到了不少,真是把设计模式用的非常好的程序员真的不多,有的程序员干了好多年的程序开发,甚至你问他都有哪些设计原则和设计模式他竟然说不全。

既然设计原则和设计模式这么重要,所以今天我就讲讲我对设计原则和设计模式的一些理解和认识。

单一职责原则

程序设计六大原则之首单一职责原则,他的主要思想是把功能相近或相似的成员变量或成员方法放在一起,类的实现保证职责单一。这个原则也是六大原则中最基本的一个原则,在早期的Android开发当中都会把业务逻辑层,数据层都放到Activity当中,这是一种非标准化的MVC架构,Activity既担任了控制层的职责又担任了View层的职责,随着业务的发展新增的功能也越来越多,就导致Activity的体积越来越庞大,长期以往整个项目就变成铁板一块,修改一个地方导致很多地方都需要修改,给后期的维护造成很大的麻烦,早期这种简单粗暴程序设计他的弊端是显而易见的,它违背了单一职责原则,解决他的主要手段就是按照职责进行分层,把业务逻辑层和数据层从Activity层剥离,就有了后来的经典MVP架构,和现在非常流行的MVVM架构,这样各层各司其职、各尽其责,我们在后期的维护开发中就非常的方便。

里氏替换原则

里氏替换原则是关于父子类之间定义的一个规则,主要的精神思想是:子类可以替换父类并可以出现在父类可以出现的任何地方。通俗的讲就是子类可以扩展父类的功能,但是不能覆盖父类的原有功能,他主要包含了有以下几层含义,子类可以实现父类的抽象方法,但是不能覆盖父类的非抽象方法;子类可以扩展自己的自有方法;子类重载父类的方法的时候方法的前置条件要尽量的宽松;子类实现父类抽象的方法的时候方法的后置条件要更加的严格。

依赖倒置原则

接下来我们看依赖导致原则,依赖抽象而不依赖具体,其核心思想就是面向接口编程,主要包含了以下几层含义:底层应该依赖抽象类或接口;成员变量的声明尽量用抽象类或接口。

里氏替换原则和依赖倒置原则的主要区别在于,里氏替换原则是关于父类和子类之间的原则,而依赖倒置原则是关于抽象和具体之间的原则,显然依赖倒置原则的应用范围比里氏替换原则的应用范围更加的广泛。

接口隔离原则

接口隔离原则主要是讲一个类对另外一个类的依赖应建立在最小的接口上,接口的设计越小越好,接口的设计要保证精简单一。

迪米特原则

迪米特原则主要的精神思想是一个类应尽量减少对一个类的了解,只和直接的朋友打交道,不和陌生人说话,尽量的降低一个类的访问权限,他的主要作用就是要降低代码之间的耦合度。

开闭原则

开闭原则可以说是程序设计六大原则总的指导思想,也是最为抽象的一个原则,主要是讲程序对外地扩展是开放的,对内的修改的是关闭的,开闭原则在面向对象设计中的地位就好比牛顿第一定律在力学,勾股定理在几何学的地位,其地位无人能及。

组合聚合复用原则

组合聚合复用原则这是程序设计第七大原则,优先使用组合聚合,其次再考虑使用继承。

创建型

说完了设计原则我们再看设计模式,设计模式是人们在长期的编程实践中所总结归纳的一套解决某些特定问题通用的模板、方法与技巧。

单例

确保一个类只有一个实例对象存在,而且自行实例化,自行提供对外访问的接口
在这里插入图片描述

  • 饿汉式单例:
/**
 * Description: <饿汉式单利><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Singleton {
    private static Singleton singleton = new Singleton();

    public static Singleton getSingleton() {
        return singleton;
    }
}
  • 懒汉式单例:
/**
 * Description: <懒汉式单例><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Singleton1 {
    private static Singleton1 mSingleton;

    public static Singleton1 getInstance() {
        if (mSingleton == null) {
            synchronized (Singleton1.class) {
                if (mSingleton == null) {
                    mSingleton = new Singleton1();
                }
            }
        }
        return mSingleton;
    }
}
  • 静态内部类的懒汉式单例:
/**
 * Description: <推荐的单例模式><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Singleton2 {

    public static Singleton2 getSingleton() {
        return SingletonHelpter.singleton;
    }

    static class SingletonHelpter {
        public static Singleton2 singleton = new Singleton2();
    }
}

建造者模式

将一个复杂对象的创建和表示相分离,用相同的构建过程创建出不同的对象表示
在这里插入图片描述

/**
 * Description: <IPersonBuilder><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IPersonBuilder {
    String createHeader();
    String createBody();
    String createFooter();
}
/**
 * Description: <PersonThinBuilder><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class PersonFatBuilder implements IPersonBuilder {
    @Override
    public String createHeader() {
        return "胖头";
    }

    @Override
    public String createBody() {
        return "胖腰";
    }

    @Override
    public String createFooter() {
        return "胖腿";
    }
}
/**
 * Description: <PersonThinBuilder><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class PersonThinBuilder implements IPersonBuilder {
    @Override
    public String createHeader() {
        return "瘦头";
    }

    @Override
    public String createBody() {
        return "瘦腰";
    }

    @Override
    public String createFooter() {
        return "瘦腿";
    }
}
/**
 * Description: <APerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Person {
    private String header;
    private String body;
    private String footer;

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getFooter() {
        return footer;
    }

    public void setFooter(String footer) {
        this.footer = footer;
    }

    @Override
    public String toString() {
        return "APerson{" +
                "header='" + header + '\'' +
                ", body='" + body + '\'' +
                ", footer='" + footer + '\'' +
                '}';
    }
}
/**
 * Description: <BuilderHandler><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class BuilderHandler {
    public Person createPerson(IPersonBuilder builder){
        Person person = new Person();
        String header = builder.createHeader();
        String body = builder.createBody();
        String footer = builder.createFooter();
        person.setHeader(header);
        person.setBody(body);
        person.setFooter(footer);
        System.out.println(person.toString());
        return person;
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        PersonFatBuilder personFatBuilder = new PersonFatBuilder();
        PersonThinBuilder personThinBuilder = new PersonThinBuilder();
        BuilderHandler builderHandler = new BuilderHandler();
        Person fatPerson = builderHandler.createPerson(personFatBuilder);
        Person thinPerson = builderHandler.createPerson(personThinBuilder);
    }
}

简单工厂模式

定义一个创建对象的静态方法,根据传递参数的不同创建出不同类型的对象
在这里插入图片描述

/**
 * Description: <ITv><br>
 * Author:      mxdl<br>
 * Date:        2019/12/18<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IOperate {
    int operate(int a, int b);
}
/**
 * Description: <OperateAdd><br>
 * Author:      mxdl<br>
 * Date:        2019/12/18<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class OperateAdd implements IOperate {
    @Override
    public int operate(int a, int b) {
        return a + b;
    }
}
/**
 * Description: <OperateAdd><br>
 * Author:      mxdl<br>
 * Date:        2019/12/18<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class OperateSub implements IOperate {
    @Override
    public int operate(int a, int b) {
        return a - b;
    }
}
/**
 * Description: <OperateAdd><br>
 * Author:      mxdl<br>
 * Date:        2019/12/18<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class OperateMul implements IOperate {
    @Override
    public int operate(int a, int b) {
        return a * b;
    }
}
/**
 * Description: <OperateAdd><br>
 * Author:      mxdl<br>
 * Date:        2019/12/18<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class OperateDiv implements IOperate {
    @Override
    public int operate(int a, int b){
        if(b == 0){
            try {
                throw new Exception("除数不能为0");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return a / b;
    }
}
/**
 * Description: <SimpleFactory><br>
 * Author:      mxdl<br>
 * Date:        2019/12/18<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class SimpleFactory {
    public static IOperate createOperation(String operate) {
        switch (operate) {
            case "+":
                return new OperateAdd();
            case "-":
                return new OperateSub();
            case "*":
                return new OperateMul();
            case "/":
                return new OperateDiv();
        }
        return null;
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        IOperate operation = SimpleFactory.createOperation("+");
        int operate = operation.operate(12, 3);
        System.out.println("计算结果:"+operate);
    }
}

工厂方法模式

定义一个创建对象的接口,具体的创建类型由子类完成
在这里插入图片描述

/**
 * Description: <ITv><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IOperate {
    int operate(int left,int right);
}
/**
 * Description: <IOperateFactory><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IOperateFactory {
    IOperate createOperate();
}
/**
 * Description: <OperateAdd><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class OperateAdd implements IOperate {
    @Override
    public int operate(int left, int right) {
        return left + right;
    }
}
/**
 * Description: <OperateAdd><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class OperateSub implements IOperate {

    @Override
    public int operate(int left, int right) {
        return left - right;
    }
}
/**
 * Description: <AddFactory><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class AddFactory implements IOperateFactory {
    @Override
    public IOperate createOperate() {
        return new OperateAdd();
    }
}
/**
 * Description: <SubFactory ><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class SubFactory implements IOperateFactory {
    @Override
    public IOperate createOperate() {
        return new OperateSub();
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        IOperate addPerrate = new AddFactory().createOperate();
        int operate1 = addPerrate.operate(12, 22);
        System.out.println("计算结果:"+operate1);

        IOperate IOperate = new SubFactory().createOperate();
        int operate2 = IOperate.operate(12, 2);
        System.out.println("计算结果1:"+operate2);

    }
}

抽象工厂模式

定义一个创建一组相关或具有相互依赖关系的对象的接口,而且无需指定他们的具体类型
在这里插入图片描述

/**
 * Description: <APerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IPerson {
    void eat();
    void sleep();
    void study();
}
/**
 * Description: <IPersonFactory><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IPersonFactory {
    IPerson createWhitePerson();
    IPerson createBlackPerson();
    IPerson createYellowPerson();
}
/**
 * Description: <YellowPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class BlackPerson implements IPerson {
    @Override
    public void eat() {
        System.out.println("BlackPerson eat");
    }

    @Override
    public void sleep() {
        System.out.println("BlackPerson sleep");
    }

    @Override
    public void study() {
        System.out.println("BlackPerson study");
    }
}
/**
 * Description: <YellowPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class BlackManPerson extends BlackPerson {
    @Override
    public void eat() {
        System.out.println("BlackManPerson eat");
    }

    @Override
    public void sleep() {
        System.out.println("BlackManPerson sleep");
    }

    @Override
    public void study() {
        System.out.println("BlackManPerson study");
    }
}
/**
 * Description: <YellowPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class BlackWomanPerson extends BlackPerson {
    @Override
    public void eat() {
        System.out.println("BlackWomanPerson eat");
    }

    @Override
    public void sleep() {
        System.out.println("BlackWomanPerson sleep");
    }

    @Override
    public void study() {
        System.out.println("BlackWomanPerson study");
    }
}
/**
 * Description: <YellowPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class YellowPerson implements IPerson {
    @Override
    public void eat() {
        System.out.println("YellowPerson eat");
    }

    @Override
    public void sleep() {
        System.out.println("YellowPerson sleep");
    }

    @Override
    public void study() {
        System.out.println("YellowPerson study");
    }
}
/**
 * Description: <YellowManPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class YellowManPerson extends YellowPerson {
    @Override
    public void eat() {
        System.out.println("YellowManPerson eat");
    }

    @Override
    public void sleep() {
        System.out.println("YellowManPerson sleep");
    }

    @Override
    public void study() {
        System.out.println("YellowManPerson study");
    }
}
/**
 * Description: <YellowWomanPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class YellowWomanPerson extends YellowPerson {
    @Override
    public void eat() {
        System.out.println("YellowWomanPerson eat");
    }

    @Override
    public void sleep() {
        System.out.println("YellowWomanPerson sleep");
    }

    @Override
    public void study() {
        System.out.println("YellowWomanPerson study");
    }
}
/**
 * Description: <YellowPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class WhitePerson implements IPerson {
    @Override
    public void eat() {
        System.out.println("WhitePerson eat");
    }

    @Override
    public void sleep() {
        System.out.println("WhitePerson sleep");
    }

    @Override
    public void study() {
        System.out.println("WhitePerson study");
    }
}
/**
 * Description: <YellowPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class WhiteManPerson extends WhitePerson {
    @Override
    public void eat() {
        System.out.println("WhiteManPerson eat");
    }

    @Override
    public void sleep() {
        System.out.println("WhiteManPerson sleep");
    }

    @Override
    public void study() {
        System.out.println("WhiteManPerson study");
    }
}
/**
 * Description: <YellowPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class WhiteWomanPerson extends WhitePerson {
    @Override
    public void eat() {
        System.out.println("WhiteWomanPerson eat");
    }

    @Override
    public void sleep() {
        System.out.println("WhiteWomanPerson sleep");
    }

    @Override
    public void study() {
        System.out.println("WhiteWomanPerson study");
    }
}
/**
 * Description: <ManFactory><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class ManFactory implements IPersonFactory {
    @Override
    public IPerson createWhitePerson() {
        return new WhiteManPerson();
    }

    @Override
    public IPerson createBlackPerson() {
        return new BlackManPerson();
    }

    @Override
    public IPerson createYellowPerson() {
        return new YellowManPerson();
    }
}
/**
 * Description: <ManFactory><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class WomanFactory implements IPersonFactory {
    @Override
    public IPerson createWhitePerson() {
        return new WhiteWomanPerson();
    }

    @Override
    public IPerson createBlackPerson() {
        return new WhiteWomanPerson();
    }

    @Override
    public IPerson createYellowPerson() {
        return new YellowWomanPerson();
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        ManFactory manFactory = new ManFactory();
        IPerson whitePerson = manFactory.createWhitePerson();
        IPerson yellowPerson = manFactory.createYellowPerson();
        IPerson blackPerson = manFactory.createBlackPerson();

        whitePerson.eat();
        yellowPerson.eat();
        blackPerson.eat();
    }
}

原型模式

由原型对象来指定创建对象的类型,并通过拷贝原型对象来创建新的对象
在这里插入图片描述

/**
 * Description: <APerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class APerson {
    private String name;
    private int age;

    public APerson(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "APerson{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
/**
 * Description: <CopyPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class CopyPerson extends APerson {
    public CopyPerson(String name, int age) {
        super(name, age);
    }
    public CopyPerson() {
        super(null,0);
    }
}
/**
 * Description: <PrototypePerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class PrototypePerson extends APerson {
    public PrototypePerson(String name, int age) {
        super(name, age);
    }
    public APerson clonePerson(){
        CopyPerson copyPerson = new CopyPerson();
        copyPerson.setName(getName());
        copyPerson.setAge(getAge());
        return copyPerson;
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/23<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        PrototypePerson prototypePerson = new PrototypePerson("张三",18);
        System.out.println(prototypePerson.toString());
        APerson aPerson = prototypePerson.clonePerson();
        prototypePerson.setName("李四");
        prototypePerson.setAge(16);

        System.out.println(prototypePerson.toString());
        System.out.println(aPerson.toString());
    }
}

结构型

适配器模式

将一个接口转换为客户所需要的另外一个接口,使原来由于接口不兼容而不能在一起工作的两个类能够在一起正常工作
在这里插入图片描述

/**
 * Description: <QiaoDan><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class QiaoDan extends APlayer {

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

    @Override
    public void attack() {
        System.out.println("QiaoDan start attack...");
    }

    @Override
    public void defense() {
        System.out.println("QiaoDan start defense...");
    }
}
/**
 * Description: <KeBi><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class KeBi extends APlayer {

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

    @Override
    public void attack() {
        System.out.println("KeBi start attack...");
    }

    @Override
    public void defense() {
        System.out.println("KeBi start defense...");
    }
}
/**
 * Description: <YaoMing><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class YaoMing {
    private String name;

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

    public void chinaAttack() {
        System.out.println("YaoMing start attack...");
    }

    public void chinaDefense() {
        System.out.println("YaoMing start defense...");
    }
}
/**
 * Description: <TranslaterAdapter><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class TranslaterAdapter extends APlayer {
    private YaoMing mYaoMing;
    public TranslaterAdapter(String name) {
        super(name);
       mYaoMing = new YaoMing("YaoMing");
    }

    @Override
    public void attack() {
        mYaoMing.chinaAttack();
    }

    @Override
    public void defense() {
        mYaoMing.chinaDefense();
    }
}

代理模式

给一个对象提供一个代理对象来控制对该对象的访问
在这里插入图片描述

/**
 * Description: <IGame><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IGame {
    void login();
    void palyer();
}
/**
 * Description: <GamePlayer><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class GamePlayer implements IGame {
    @Override
    public void login() {
        System.out.println("GamePlayer start login...");
    }

    @Override
    public void palyer() {
        System.out.println("GamePlayer start palyer...");
    }
}
/**
 * Description: <GamePoxy><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class GamePoxy implements IGame {
    private IGame mGame;

    public GamePoxy(IGame game) {
        this.mGame = game;
    }

    @Override
    public void login() {
        mGame.login();
    }

    @Override
    public void palyer() {
        mGame.palyer();
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        GamePoxy gamePoxy = new GamePoxy(new GamePlayer());
        gamePoxy.login();
        gamePoxy.palyer();
    }
}

装饰模式

动态的给一个对象增加一些额外的功能,使它变得更加强大
在这里插入图片描述

/**
 * Description: <IPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IPerson {
    void eat();
}
/**
 * Description: <APerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Person implements IPerson {
    @Override
    public void eat() {
        System.out.println("开始吃饭");
    }
}
/**
 * Description: <SuperPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class SuperPerson implements IPerson {
    private Person mPerson;

    public SuperPerson(Person person) {
        mPerson = person;
    }

    @Override
    public void eat() {
        System.out.println("喝一杯...");
        mPerson.eat();
        System.out.println("抽一根...");
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        SuperPerson superPerson = new SuperPerson(new Person());
        superPerson.eat();
    }
}

门面模式

将多个对象通过另外一个对象封装起来,对外提供统一的访问接口
在这里插入图片描述

/**
 * Description: <ICook><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface ICook {
    void cooking();
}
/**
 * Description: <NoodleCook><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class RiceCook implements ICook {
    @Override
    public void cooking() {
        System.out.println("炒菜米饭");
    }
}
/**
 * Description: <NoodleCook><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class NoodleCook implements ICook {
    @Override
    public void cooking() {
        System.out.println("各种面食");
    }
}
/**
 * Description: <CookManager><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class CookManager {
    private RiceCook mRiceCook;
    private NoodleCook mNoodleCook;

    public CookManager(RiceCook riceCook, NoodleCook noodleCook) {
        mRiceCook = riceCook;
        mNoodleCook = noodleCook;
    }
    public void cookRice(){
        mRiceCook.cooking();
    }
    public void cookNoodle(){
        mNoodleCook.cooking();
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        RiceCook riceCook = new RiceCook();
        NoodleCook noodleCook = new NoodleCook();
        CookManager cookManager = new CookManager(riceCook,noodleCook);
        cookManager.cookRice();
        cookManager.cookNoodle();
    }
}

享元模式

通过享元对象可以提供大量的细粒度化的对象
在这里插入图片描述

/**
 * Description: <IWebSite><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IWebSite {
    void use(User user);
}
/**
 * Description: <User><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class User {
    private String name;

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

    public String getName() {
        return name;
    }

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

/**
 * Description: <WebSite><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class WebSite implements IWebSite {
    private String name;

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

    @Override
    public void use(User user) {
        System.out.println("网站分类:"+name+";用户:"+user.getName());
    }
}
/**
 * Description: <WebSiteFactory><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class WebSiteFactory {
    private HashMap<String, WebSite> mHashMap = new HashMap<>();
    public WebSite getWebSite(String key) {
        if (!mHashMap.containsKey(key)) {
            mHashMap.put(key, new WebSite(key));
        }
        return mHashMap.get(key);
    }
    public int getWebSiteSize(){
        return mHashMap.size();
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        WebSiteFactory webSiteFactory = new WebSiteFactory();
        WebSite webSite = webSiteFactory.getWebSite("产品展示");
        webSite.use(new User("张三"));
        webSite.use(new User("李四"));
        webSite.use(new User("王五"));

        WebSite webSite1 = webSiteFactory.getWebSite("博客");
        webSite1.use(new User("张三"));
        webSite1.use(new User("李四"));

        System.out.println("网站分类总数:"+webSiteFactory.getWebSiteSize());
    }
}

桥梁模式

将一个对象的抽象和实现相分离,使二者可以相对独立变化
在这里插入图片描述

/**
 * Description: <APhoneBrand><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public abstract class APhoneBrand {
    protected IPhoneSoftware mSoftware;

    public APhoneBrand(IPhoneSoftware software) {
        mSoftware = software;
    }

    public abstract void createBrnad();
    public void createSoftWare() {
        mSoftware.crateSoftware();
    }
}
/**
 * Description: <IPhoneSoftware><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IPhoneSoftware {
    void crateSoftware();
}
/**
 * Description: <XiaoMiBrand><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class SanXingBrand extends APhoneBrand {
    public SanXingBrand(IPhoneSoftware software) {
        super(software);
    }

    @Override
    public void createBrnad() {
        System.out.println("三星手机");
    }

}
/**
 * Description: <XiaoMiSoftware><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class SanXingSoftware implements IPhoneSoftware {
    @Override
    public void crateSoftware() {
        System.out.println("三星软件");
    }
}

/**
 * Description: <XiaoMiBrand><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class XiaoMiBrand extends APhoneBrand {
    public XiaoMiBrand(IPhoneSoftware software) {
        super(software);
    }

    @Override
    public void createBrnad() {
        System.out.println("小米手机");
    }
}
/**
 * Description: <XiaoMiSoftware><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class XiaoMiSoftware implements IPhoneSoftware {
    @Override
    public void crateSoftware() {
        System.out.println("小米软件");
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        XiaoMiBrand xiaoMiBrand = new XiaoMiBrand(new XiaoMiSoftware());
        xiaoMiBrand.createBrnad();
        xiaoMiBrand.createSoftWare();

        SanXingBrand sanXingBrand = new SanXingBrand(new SanXingSoftware());
        sanXingBrand.createBrnad();
        sanXingBrand.createSoftWare();
    }
}

组合模式

将多个单一对象组成具有一定层次关系的树形结构的组合对象,组合模式淡化了单一对象和组合对象之间的差别,使得单一对象和组合对象具有相同的处理方式
在这里插入图片描述

/**
 * Description: <INode><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface INode {
    void addNode(INode node);
    void removeNode(INode node);
}
/**
 * Description: <Leaf><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Leaf implements INode {
    @Override
    public void addNode(INode node) {

    }

    @Override
    public void removeNode(INode node) {

    }
}
/**
 * Description: <Composite><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Composite implements INode {
    private ArrayList<INode> mChildList = new ArrayList<>();

    @Override
    public void addNode(INode node) {
        mChildList.add(node);
    }

    @Override
    public void removeNode(INode node) {
        mChildList.remove(node);
    }

    public ArrayList<INode> getChildList() {
        return mChildList;
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        Leaf leaf = new Leaf();
        Leaf leaf1 = new Leaf();
        Leaf leaf2 = new Leaf();
        Composite root = new Composite();
        Composite composite = new Composite();
        Composite composite1 = new Composite();

        composite.addNode(leaf);
        composite.addNode(leaf1);
        composite1.addNode(leaf2);

        root.addNode(composite);
        root.addNode(composite1);
    }
}

行为型

模板方法

只定义一个算法的执行骨架,具体的算法实现延迟到子类完成
在这里插入图片描述

/**
 * Description: <Cat><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Cat implements IAnimal {

    @Override
    public void eat() {
        System.out.println("猫吃鱼");
    }
}
/**
 * Description: <Cat><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Dog implements IAnimal {

    @Override
    public void eat() {
        System.out.println("狗啃骨头");
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        Cat cat = new Cat();
        Dog dog = new Dog();
        cat.eat();
        dog.eat();
    }
}

策略

定义了多个算法,多个算法之间可以灵活切换
在这里插入图片描述

/**
 * Description: <ITv><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IOperate {
    int operate(int left,int right);
}
/**
 * Description: <AddOperate><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class AddOperate implements IOperate {
    @Override
    public int operate(int left, int right) {
        return left + right;
    }
}
/**
 * Description: <SubOperate><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class SubOperate implements IOperate {
    @Override
    public int operate(int left, int right) {
        return left-right;
    }
}
/**
 * Description: <Context><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Context implements IOperate{
    IOperate mOperate;

    public Context(IOperate operate) {
        mOperate = operate;
    }

    @Override
    public int operate(int left, int right) {
        return mOperate.operate(left,right);
    }

    public void setOperate(IOperate operate) {
        mOperate = operate;
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        Context context = new Context(new AddOperate());
        int operate = context.operate(12, 1);
        System.out.println(operate);

        context.setOperate(new SubOperate());
        int operate1 = context.operate(12, 1);
        System.out.println(operate1);

    }
}

责任链

当前对象持有下家对象的引用而形成一个链条,请求在这个链条上传递,直到有对象能够处理该对象的请求为止
在这里插入图片描述

/**
 * Description: <Employee><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public abstract class Employee {
    protected Employee mEmployee;

    public Employee(Employee employee) {
        mEmployee = employee;
    }

    public abstract void request(int day);
}
/**
 * Description: <SmallLeader><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class SmallLeader extends Employee {
    public SmallLeader(Employee employee) {
        super(employee);
    }

    @Override
    public void request(int day) {
        if(day<3){
            System.out.println("小领导批了");
        }else{
          mEmployee.request(day);
        }
    }
}
/**
 * Description: <SmallLeader><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class MiddleLeader extends Employee {
    public MiddleLeader(Employee employee) {
        super(employee);
    }

    @Override
    public void request(int day) {
        if(day<7){
            System.out.println("中层领导批了");
        }else{
          mEmployee.request(day);
        }
    }
}
/**
 * Description: <SmallLeader><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class BigLeader extends Employee {
    public BigLeader(Employee employee) {
        super(employee);
    }

    @Override
    public void request(int day) {
        System.out.println("大领导批了");
    }
}

观察者

定义了一种一对多的依赖关系,当被观察者发生变化时,所有的观察者都会收到通知,并且能够自动更新
在这里插入图片描述

/**
 * Description: <Observer1><br>
 * Author:      mxdl<br>
 * Date:        2019/12/19<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Observer1 implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("update 1 start...");
    }
}
/**
 * Description: <Observer1><br>
 * Author:      mxdl<br>
 * Date:        2019/12/19<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Observer2 implements Observer {
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("update 2 start...");
    }
}
/**
 * Description: <Subject><br>
 * Author:      mxdl<br>
 * Date:        2019/12/19<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Subject extends Observable {
    public void update(){
        setChanged();
        notifyObservers();
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/19<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        Observer1 observer1 = new Observer1();
        Observer2 observer2 = new Observer2();
        Subject subject = new Subject();
        subject.addObserver(observer1);
        subject.addObserver(observer2);
        subject.update();
    }
}

迭代器模式

提供一个方法来访问容器对象中的每一个元素而不暴露该对象的内部表示
在这里插入图片描述

/**
 * Description: <Student><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
/**
 * Description: <School><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class School {
    private List<Student> mList = new ArrayList<>();
    private int index = 0;
    public void addStudent(Student student){
        mList.add(student);
    }
    public void removeStudent(Student student){
        mList.remove(student);
    }
    public boolean isHave(){
        if(mList == null ||  mList.size() == 0){
            return false;
        }
        if(index <= mList.size()-1){
            return true;
        }
        return false;
    }
    public Student next(){
       return mList.get(index++);
    }
}

备忘录

在不破坏原对象封装性的前提条件下,捕获一个对象的内部状态,并把该状态保存在该对象之外,在以后可以恢复该对象为原先保存的那个状态
在这里插入图片描述

/**
 * Description: <APerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public MementtoPerson createMementtoPerson(){
        MementtoPerson mementtoPerson = new MementtoPerson();
        mementtoPerson.setName(this.name);
        mementtoPerson.setAge(this.age);
        return mementtoPerson;
    }
    public void reMementtoPerson(MementtoPerson mementtoPerson){
        this.name = mementtoPerson.getName();
        this.age = mementtoPerson.getAge();
    }

    @Override
    public String toString() {
        return "APerson{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
/**
 * Description: <MementtoPerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class MementtoPerson {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        Person person = new Person("zhangsan",18);
        System.out.println(person.toString());
        MementtoPerson mementtoPerson = person.createMementtoPerson();
        person.setAge(21);
        System.out.println(person.toString());
        person.reMementtoPerson(mementtoPerson);
        System.out.println(person.toString());
    }
}

解释器

定义一个语法算法,来解析将要执行的语句
在这里插入图片描述

/**
 * Description: <IExplain><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IExplain {
    int explain();
}
/**
 * Description: <NumberExpain><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class NumberExpain implements IExplain {
    private int value;

    public NumberExpain(int value) {
        this.value = value;
    }

    @Override
    public int explain() {
        return value;
    }
}
/**
 * Description: <AddExplain><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class AddExplain implements IExplain {
    private IExplain left;
    private IExplain right;

    public AddExplain(IExplain left, IExplain right) {
        this.left = left;
        this.right = right;
    }

    @Override
    public int explain() {
        return left.explain() + right.explain();
    }
}
/**
 * Description: <AddExplain><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class SubExplain implements IExplain {
    private IExplain left;
    private IExplain right;
    public SubExplain(IExplain left, IExplain right) {
        this.left = left;
        this.right = right;
    }
    @Override
    public int explain() {
        return left.explain() - right.explain();
    }
}
/**
 * Description: <AddExplain><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class MulExplain implements IExplain {
    private IExplain left;
    private IExplain right;
    public MulExplain(IExplain left, IExplain right) {
        this.left = left;
        this.right = right;
    }
    @Override
    public int explain() {
        return left.explain() * right.explain();
    }
}
/**
 * Description: <AddExplain><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class DevExplain implements IExplain {
    private IExplain left;
    private IExplain right;
    public DevExplain(IExplain left, IExplain right) {
        this.left = left;
        this.right = right;
    }
    @Override
    public int explain() {
        return left.explain() / right.explain();
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        //2+4*2-3
        NumberExpain expain2 = new NumberExpain(2);
        NumberExpain expain4 = new NumberExpain(4);
        NumberExpain expain3 = new NumberExpain(3);

        MulExplain mulExplain = new MulExplain(expain2,expain4);
        AddExplain addExplain = new AddExplain(expain2,mulExplain);
        SubExplain subExplain = new SubExplain(addExplain,expain3);
        int explain = subExplain.explain();
        System.out.println(explain);
    }
}

命令状态

每一个请求都封装为一个命令对象,允许系统使用不同的请求把客户端参数化,多个命令请求可以排队、撤销、恢复、记录日志等操作
在这里插入图片描述

/**
 * Description: <ITv><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface ITv {
    void turnOn();
    void turnOff();
    void changeChannel();
}
/**
 * Description: <ACommand><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public abstract class ACommand {
    protected ITv tv;

    public ACommand(ITv ITv) {
        tv = ITv;
    }

    public abstract void exeCommand();
}
/**
 * Description: <TV><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class TV implements ITv {
    @Override
    public void turnOn() {
        System.out.println("TV turnOn");
    }

    @Override
    public void turnOff() {
        System.out.println("TV turnOff");
    }

    @Override
    public void changeChannel() {
        System.out.println("TV changeChannel");
    }
}
/**
 * Description: <TurnOnCommand><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class TurnOnCommand extends ACommand {
    public TurnOnCommand(ITv ITv) {
        super(ITv);
    }

    @Override
    public void exeCommand() {
        tv.turnOn();
    }
}
/**
 * Description: <TurnOnCommand><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class TurnOffCommand extends ACommand {
    public TurnOffCommand(ITv ITv) {
        super(ITv);
    }

    @Override
    public void exeCommand() {
        tv.turnOff();
    }
}
/**
 * Description: <TurnOnCommand><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class TurnChannelCommand extends ACommand {
    public TurnChannelCommand(ITv ITv) {
        super(ITv);
    }

    @Override
    public void exeCommand() {
        tv.changeChannel();
    }
}
/**
 * Description: <CommandManager><br>
 * Author:      mxdl<br>
 * Date:        2019/12/29<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class CommandManager implements ITv {
    private TurnOnCommand mTurnOnCommand;
    private TurnOffCommand mTurnOffCommand;
    private TurnChannelCommand mTurnChannelCommand;

    public CommandManager(TurnOnCommand turnOnCommand, TurnOffCommand turnOffCommand, TurnChannelCommand turnChannelCommand) {
        mTurnOnCommand = turnOnCommand;
        mTurnOffCommand = turnOffCommand;
        mTurnChannelCommand = turnChannelCommand;
    }

    @Override
    public void turnOn() {
        mTurnOnCommand.exeCommand();
    }

    @Override
    public void turnOff() {
        mTurnOffCommand.exeCommand();
    }

    @Override
    public void changeChannel() {
        mTurnChannelCommand.exeCommand();
    }
}

状态模式

当一个对象在状态改变的时候允许改变他的行为,使对象看起来像是改变了他的类
在这里插入图片描述

/**
 * Description: <IState><br>
 * Author:      mxdl<br>
 * Date:        2019/12/26<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IState {
    void onPress(Light light);
}
/**
 * Description: <StateClose><br>
 * Author:      mxdl<br>
 * Date:        2019/12/26<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class StateOpen implements IState {
    @Override
    public void onPress(Light light) {
        System.out.println("打开状态");
        light.setIState(new StateClose());
    }
}
/**
 * Description: <StateClose><br>
 * Author:      mxdl<br>
 * Date:        2019/12/26<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class StateClose implements IState {
    @Override
    public void onPress(Light light) {
        System.out.println("关闭状态");
        light.setIState(new StateOpen());
    }
}
/**
 * Description: <Light><br>
 * Author:      mxdl<br>
 * Date:        2019/12/26<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Light {
    private IState mIState;
    public Light(){
        mIState = new StateClose();
    }
    public void onPress(){
        mIState.onPress(this);
    }

    public void setIState(IState IState) {
        this.mIState = IState;
    }
}

中介者模式

将多个对象之间多对多的网状关系变成一对多的星状关系
在这里插入图片描述

/**
 * Description: <ICountry><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface ICountry {
    void sendMessage(String message);
    void notifyMessage(String messaege);
}
/**
 * Description: <IUN><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IUN {
    void sendMessage(String msg, ICountry country);
}
/**
 * Description: <Usa><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Usa implements ICountry {
    IUN mIUN;

    public Usa(IUN IUN) {
        mIUN = IUN;
    }

    @Override
    public void sendMessage(String message) {
        mIUN.sendMessage(message,this);
    }

    @Override
    public void notifyMessage(String messaege) {
        System.out.println("美国收到了消息:"+messaege);
    }
}
/**
 * Description: <Usa><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Irap implements ICountry {
    IUN mMediator;

    public Irap(IUN mediator) {
        mMediator = mediator;
    }

    @Override
    public void sendMessage(String message) {
        mMediator.sendMessage(message,this);
    }

    @Override
    public void notifyMessage(String messaege) {
        System.out.println("伊拉克收到了消息:"+messaege);
    }
}
/**
 * Description: <UN><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class UN implements IUN {
    private Usa mUsa;
    private Irap mIrap;

    public void setUsa(Usa usa) {
        mUsa = usa;
    }

    public void setIrap(Irap irap) {
        mIrap = irap;
    }

    @Override
    public void sendMessage(String msg, ICountry country) {
        if(country == mUsa){
            mIrap.notifyMessage(msg);
        }else if(country == mIrap){
            mUsa.notifyMessage(msg);
        }
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        UN un = new UN();
        Usa usa = new Usa(un);
        Irap irap = new Irap(un);
        un.setUsa(usa);
        un.setIrap(irap);
        usa.sendMessage("不要研究核武器,否则将发生战争");
        irap.sendMessage("我们没有研究核武器,我们也不怕侵略");
    }
}

访问者模式

将对象的表示和行为相分离,适合数据结构比较稳定的数据
在这里插入图片描述

/**
 * Description: <IVistor><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public interface IVistor {
    void processManState(Man man);
    void processWomanState(Woman woman);
}
/**
 * Description: <APerson><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public abstract class APerson {
    private String name;

    protected abstract void accept(IVistor vistor);

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
/**
 * Description: <Man><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Man extends APerson {
    public Man(String name) {
        super(name);
    }

    @Override
    public void accept(IVistor vistor) {
        vistor.processManState(this);
    }
}
/**
 * Description: <Woman><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Woman extends APerson {
    public Woman(String name) {
        super(name);
    }

    @Override
    public void accept(IVistor vistor) {
        vistor.processWomanState(this);
    }
}
/**
 * Description: <SuccVistor><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class SuccVistor implements IVistor {
    @Override
    public void processManState(Man man) {
        System.out.println("成功状态:" + man.getName() + "成功男人背后都有一个伟大的女人");
    }

    @Override
    public void processWomanState(Woman woman) {
        System.out.println("成功状态:" + woman.getName() + "成功女人背后都有一个失败的男人");
    }
}
/**
 * Description: <SuccVistor><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class FailVistor implements IVistor {
    @Override
    public void processManState(Man man) {
        System.out.println("失败状态:" + man.getName() + " 低头喝闷酒,谁也劝不动");
    }

    @Override
    public void processWomanState(Woman woman) {
        System.out.println("失败状态:" + woman.getName() + " 两眼泪汪汪,谁说也不听");
    }
}
/**
 * Description: <Client><br>
 * Author:      mxdl<br>
 * Date:        2019/12/20<br>
 * Version:     V1.0.0<br>
 * Update:     <br>
 */
public class Client {
    public static void main(String[] args) {
        Man man = new Man("zhang san");
        Woman woman = new Woman("li si");
        SuccVistor succVistor = new SuccVistor();
        FailVistor failVistor = new FailVistor();

        man.accept(succVistor);
        woman.accept(succVistor);

        man.accept(failVistor);
        woman.accept(failVistor);
    }
}

创建型大PK

创建型模式包括单例模式、建造者模式、简单工厂模式、工厂方法模式、抽象工厂模式和原型模式,它们都能够提供对象的创建和管理职责。其中的单例模式和原型模式非常容易理解,单例模式是要保持在内存中只有一个对象,原型模式是要求通过复制的方式产生一个新的对象,这两个不容易混淆。简单工厂模式违背了开闭原则不建议使用,剩下的就是工厂方法模式、抽象工厂模式和建造者模式了,这三个之间有较多的相似性,工厂方法模式注重的是整体对象的构建,建造者模式注重的是对象部件的构建过程,更注重于通过一步步的精准构建创建一个复杂的对象,而抽象工厂创建的是一个产品家族,一个产品家族是一系列的产品,是具有不同分类纬度的产品组合。

结构型大PK

结构型模式主要包括适配器模式、代理模式、装饰模式、门面模式、享元模式、桥梁模式、组合模式,为什么叫组合模式?因为他们通过组合类或对象产生一个更大的结构以适应更高层次的逻辑要求,其中适配器模式和代理模式装饰模式具有很高的相似性,他们的主要的区别在于:适配器模式是你会做的我也会做,你不会做的的我也会做,它强调的是适配兼容,而代理模式是你会做的你不做我帮你做,它强调的是对对象的控制;装饰模式是你会做的你不做我帮你做而且还做的比你好,它强调的是对原对象功能的增强。

行为型的大PK

行为类模式包括模板方法模式、策略模式、责任链模式、观察者模式、迭代器模式、备忘录模式、解释器模式、命令模式、状态模式、中介者模式、访问者模式。该组真可谓是人才济济,高手如云。其中策略模式和命令模式看起来很相似,但是策略模式强调的是对算法的封装而且他们之间可以相互切换,而命令模式强调的是对一个对象的行为进行拆分,解耦,把一个对象的行为拆分为执行对象和执行行为,让两者相对独立互不干扰。策略模式和状态模式,策略模式强调的是算法的封装,而状态模式强调的是状态的转换时行为的转换。

总结

建造者模式分离了对象的创建和表示,桥梁模式分离了对象的抽象和实现,访问者模式分离对象的访问和表示

  • 用抽象构建框架,用实现扩展细节
  • 单一职责原则告诉我们实现类要职责单一
  • 里氏替换原则告诉我们不要破坏继承体系
  • 接口隔离原则告诉我们在设计接口的时候要精简单一
  • 依赖倒置原则告诉我们要面向接口编程
  • 迪米特法则告诉我们要降低耦合
  • 而开闭原则是总纲,他告诉我们要对扩展开放,对修改关闭

问题反馈

在使用学习中有任何问题,请留言,或加入Android、Java开发技术交流群

  • QQ群:810970432
  • email:geduo_83@163.com
  • 公众号
    在这里插入图片描述
  • 技术群
©️2020 CSDN 皮肤主题: 撸撸猫 设计师: 设计师小姐姐 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值