一文总结设计模式

2020-11-23  本文已影响0人  小呆呆666

前言

总述

7种面向对象设计原则

设计原则名称 定 义
单一职责原则(Single Responsibility Principle, SRP) 一个类只负责一个功能领域中的相应职责
开闭原则(Open-Closed Principle, OCP) 软件实体应对扩展开放,而对修改关闭
里氏代换原则(Liskov Substitution Principle, LSP) 所有引用基类对象的地方能够透明地使用其子类的对象
迪米特法则(Law of Demeter, LoD) 一个软件实体应当尽可能少地与其他实体发生相互作用
接口隔离原则(Interface Segregation Principle, ISP) 使用多个专门的接口,而不使用单一的总接口
依赖倒转原则(Dependence Inversion Principle, DIP) 抽象不应该依赖于细节,细节应该依赖于抽象
合成复用原则(Composite Reuse Principle, CRP) 尽量使用对象组合,而不是继承来达到复用的目的

原则简述

1. 单一职责原则

定义:一个类只有一个引起它变化的原因。

理解:对功能进行分类,代码进行解耦,一个类只管一件事

举例:就比如一个网络请求框架大体分为:请求类,缓存类,配置类,不能把这3个混在一起,必须分为3个类去实现不同的功能。

2.开闭原则

定义:一个实体(类、函数、模块等)应该对外扩展开放,对内修改关闭

理解:每次发生变化时,要通过新增代码来增强现有类型的行为,而不是修改原有代码。

举例:就比如在软件的生命周期内,因为产品迭代,软件升级维护等原因,需要对原有代码进行修改时,可能会给原有代码引入错误,也可能使得我们对整个功能不得不进行重构,并且需要对原有代码进行重新测试,这样的话,对开发周期影响很大,所以开闭原则刚好解决这个问题。

3. 里氏替换原则

定义:继承必须确保超类所拥有的性质在子类中仍然成立。

理解:在继承类时,除了扩展一些新的功能之外,尽量不要删除或者修改对父类方法的引用,也尽量不要重载父类的方法。

举例:你看啊,就比如Object有个方法,叫equals,如果不遵守里氏代替原则,它的子类重载了equals这个方法,并且返回了个null,这个子类的下一个继承者也会返回null,那么,在不同开发人员开发时,可能考虑不到这个问题,那么就可能导致程序崩溃。

4.迪米特法则

定义:一个模块或对象应尽量少的与其他实体之间发生相互作用,使得系统功能模块相对独立,这样当一个模块修改时,影响的模块就会越少,扩展起来更加容易。

理解:一个对象应该对其他对象有最少的了解;一个类应该对自己需要耦合或调用的类知道得最少,类的内部如何实现、如何复杂都与调用者或者依赖者没关系,调用者或者依赖者只需要知道他需要的方法即可,其他的一概不关心。类与类之间的关系越密切,耦合度越大,当一个类发生改变时,对另一个类的影响也越大。

举例:一般在使用框架的时候,框架的开发者会抽出一个类供外部调用,而这个主要的类像是一个中介一样去调用框架里面的其他类,恰恰框架里面其他类一般都是不可访问(调用)的,这个框架就遵守了迪米特原则,其他开发人员只关心调用的方法,并不需要关心功能具体如何实现。

5.接口隔离原则

定义:使用多个专门功能的接口,而不是使用单一的总接口

理解:在定义接口方法时应该合理化,尽量追求简单最小,避免接口臃肿

举例:在实际开发中,往往为了节省时间,可能会将多个功能的方法抽成一个接口,其实这设计理念不正确的,这样会使接口处于臃肿的状态,这时就需要合理的拆分接口中的方法,另外抽取成一个独立的接口,避免原有的接口臃肿导致代码理解困难。

6.依赖倒置原则

定义:细节应该依赖于抽象,而抽象不应该依赖于细节

理解:高层模块不依赖低层次模块的细节,不依赖具体的类,而是依赖于接口

举例:比如说我们写一个网络框架,为了满足不同开发者的需求,即能使用高效的OkHttp框架,也可以使用原生的API。那么是如何进行切换的呢,这个时候需要面向接口编程思想了,把一些网络请求的方法封装成一个接口,然后分别创建OkHttp和原生API的接口实现类,当然也可以扩展其他网络框架的应用。

7.合成复用原则

定义:尽量使用对象组合,而不是继承来达到复用的目的。

理解:它要求在软件复用时,要尽量先使用组合或者聚合等关联关系来实现,其次才考虑使用继承关系来实现。

举例:相当于我们开发软件,一个模块的构造,就像搭积木一样,通过组合的形式,完成整体的构建;现在声明式UI框架,对于这种思想比较贯彻。

参考

创建型模式

单例模式

饿汉模式

public class Singleton {
    // 只会实例化一次
    private static Singleton instance = new Singleton();       
 
    // 私有构造方法,防止被实例化
    private Singleton() {}
 
    public static Singleton getInstance() {
        return instance;
    }
}

懒汉模式

public class Singleton {
    // 持有私有静态实例,防止被引用;赋值为null,目的是实现延迟加载;volatile修饰是禁止重排
    private volatile static Singleton instance = null;
 
    // 私有构造方法,防止被实例化
    private Singleton() {}
 
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (instance) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

静态内部类模式

public class Singleton {
    // 私有构造方法,防止被实例化
    private Singleton() {}
 
    // 获取实例
    public static Singleton getInstance() {
        return Inner.instance;
    }
 
    // 使用一个内部类来维护单例,只有在该类被加载的时候,才会实例化对象
    private static class Inner {
        private static Singleton instance = new Singleton();
    }
}

枚举模式

public enum Singleton {
    // 创建一个枚举对象,该对象天生为单例
    INSTANCE;
    public Singleton getInstance(){
        return INSTANCE;
    }
}

参考

工厂模式

简单工厂模式

public interface Phone {
    //实施开机操作的时候,返回手机系统
    String startUp();
}
public class AndroidPhone implements Phone {
    @Override
    public String startUp() {
        return "Android";
    }
}
public class IOSPhone implements Phone {
    @Override
    public String startUp() {
        return "IOS";
    }
}
public class PhoneFactory {
    private static Phone mPhone;

    //根据系统关键字获取相应手机对象
    public static Phone createPhone(String system) {
        switch (system) {
            case "Android":
                mPhone = new AndroidPhone();
                break;
            case "IOS":
                mPhone = new IOSPhone();
                break;
        }
        return mPhone;
    }
}
public void test() {
    Phone android = PhoneFactory.createPhone("Android");
    Phone ios = PhoneFactory.createPhone("IOS");

    System.out.print(android.startUp() + "\n");
    System.out.print(ios.startUp() + "\n");
}

工厂模式

public interface PhoneFactory {
    //获取相关手机实例
    Phone getPhone();
}
public class AndroidPhoneFactory implements PhoneFactory {
    @Override
    public Phone getPhone() {
        return new AndroidPhone();
    }
}
public class IOSPhoneFactory implements PhoneFactory {
    @Override
    public Phone getPhone() {
        return new IOSPhone();
    }
}
public void test() {
    PhoneFactory androidMiFactory = new AndroidPhoneFactory();
    PhoneFactory iosFactory = new IOSPhoneFactory();

    System.out.print(androidFactory.getPhone().startUp() + "\n");
    System.out.print(iosFactory.getPhone().startUp() + "\n");
}

抽象工厂模式

1、第一种方式

public interface PhoneSystem {
    //获取Android手机实例
    Phone getAndroid();
    
    //获取IOS手机实例
    Phone getIOS();
}
public class PhoneFactory implements PhoneSystem {
    @Override
    public Phone getAndroid() {
        return new AndroidPhone();
    }

    @Override
    public Phone getIOS() {
        return new IOSPhone();
    }
}
public void test() {
    PhoneSystem phoneSystem = new PhoneFactory();

    Phone android = phoneSystem.getXiaoMi();
    Phone ios = phoneSystem.getHuaWei();

    System.out.print(android.startUp() + "\n");
    System.out.print(ios.startUp() + "\n");
}

2、第二种方式

public class PhoneFactory {
    private static Phone instance;
    //模拟个数据
    private String SYSTEM = "IOS";

    public static Phone getInstance() {
        if("Android".equals(SYSTEM))
        {
            return new AndroidPhone();
        }
        if("IOS".equals(SYSTEM))
        {
            return new IOSPhone();
        }
        return null;
    }
}
public static void test() {
    Phone phone = PhoneFactory.getInstance();
    if (phone == null) 
        return;
    System.out.print(phone.startUp() + "\n");
}

建造者模式

说明

  1. 在Computer 中创建一个静态内部类 Builder,然后将Computer 中的参数都复制到Builder类中。
  2. 在Computer中创建一个private的构造函数,参数为Builder类型
  3. 在Builder中创建一个public的构造函数,参数为Computer中必填的那些参数,cpu 和ram。
  4. 在Builder中创建设置函数,对Computer中那些可选参数进行赋值,返回值为Builder类型的实例
  5. 在Builder中创建一个build()方法,在其中构建Computer的实例并返回

实现

public class Computer {
    private final String cpu;//必须
    private final String ram;//必须
    private final int usbCount;//可选
    private final String keyboard;//可选
    private final String display;//可选

    private Computer(Builder builder){
        this.cpu=builder.cpu;
        this.ram=builder.ram;
        this.usbCount=builder.usbCount;
        this.keyboard=builder.keyboard;
        this.display=builder.display;
    }
    
    public static class Builder{
        private String cpu;//必须
        private String ram;//必须
        private int usbCount;//可选
        private String keyboard;//可选
        private String display;//可选

        public Builder(String cup,String ram){
            this.cpu=cup;
            this.ram=ram;
        }

        public Builder setUsbCount(int usbCount) {
            this.usbCount = usbCount;
            return this;
        }
        public Builder setKeyboard(String keyboard) {
            this.keyboard = keyboard;
            return this;
        }
        public Builder setDisplay(String display) {
            this.display = display;
            return this;
        }        
        public Computer build(){
            return new Computer(this);
        }
    }
}

使用

Computer computer = new Computer.Builder("因特尔","三星")
    .setDisplay("三星24寸")
    .setKeyboard("罗技")
    .setUsbCount(2)
    .build();

参考

原型模式

定义

实现

public class Prototype implements Cloneable, Serializable {
    private static final long serialVersionUID = 1L;
    private String string;
    private SerializableObject obj;
 
    // 浅复制
    public Object clone() throws CloneNotSupportedException {
        Prototype proto = (Prototype) super.clone();
        return proto;
    }
 
    // 深复制
    public Object deepClone() throws IOException, ClassNotFoundException {
        // 写入当前对象的二进制流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);
 
        // 读出二进制流产生的新对象 
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return ois.readObject();
    }
 
    public String getString() {
        return string;
    }
 
    public void setString(String string) {
        this.string = string;
    }
 
    public SerializableObject getObj() {
        return obj;
    }
 
    public void setObj(SerializableObject obj) {
        this.obj = obj;
    }
}
 
class SerializableObject implements Serializable {
    private static final long serialVersionUID = 1L;
}

参考

结构型模式

适配器模式

类适配

public class Adaptee {
    public void adapteeRequest() {
        System.out.println("被适配者的方法");
    }
}
public interface Target {
    void request();
}
public class Adapter extends Adaptee implements Target{
    @Override
    public void request() {
        System.out.println("concreteTarget目标方法");
        super.adapteeRequest();
    }
}
public class Test {
    public static void main(String[] args) {
        Target adapterTarget = new Adapter();
        adapterTarget.request();
    }
}
concreteTarget目标方法
被适配者的方法

对象适配

public interface AC {
    int outputAC();
}

public class AC220 implements AC {
    public final int output = 220;

    @Override
    public int outputAC() {
        return output;
    }
}
public interface DC5Adapter {
    int outputDC5V(AC ac);
}
public class PowerAdapter implements DC5Adapter {
    public static final int voltage = 220; 
    
    @Override
    public int outputDC5V(AC ac) {
        int adapterInput = ac.outputAC();
        //变压器...
        int adapterOutput = adapterInput / 44;
        System.out.println("使用PowerAdapter变压适配器,输入AC:" + adapterInput + "V" 
                           + ",输出DC:" + adapterOutput + "V");
        return adapterOutput;
    }
}
public class Test {
    private List<DC5Adapter> adapters = new LinkedList<DC5Adapter>();

    public static void main(String[] args) {
        AC ac = new AC220(); //实例化220v对象
        DC5Adapter adapter = new PowerAdapter(); //实例化适配器
        adapter.outputDC5V(ac); 
    }
}
使用PowerAdapter变压适配器,输入AC:220V,输出DC:5V

接口适配

public interface Sourceable {
    public void method1();
    public void method2();
}
public abstract class Wrapper implements Sourceable{
    public void method1(){}
    public void method2(){}
}
public class SourceSub extends Wrapper {
    @Override
    public void method1(){
        System.out.println("实现方法一");
    }
}

参考

装饰模式

定义

实现

public interface Shape {
    void draw();
}
public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Shape: Rectangle");
    }
}
public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Shape: Circle");
    }
}
public abstract class ShapeDecorator implements Shape {
    protected Shape decoratedShape;

    public ShapeDecorator(Shape decoratedShape){
        this.decoratedShape = decoratedShape;
    }

    @Override
    public void draw(){
        decoratedShape.draw();
        System.out.println("Border Color: Red");
    }  
}
public class Test {
    public static void main(String[] args) {
        Shape circle = new Circle();
        ShapeDecorator circleShape = new ShapeDecorator(new Circle());
        ShapeDecorator rectangleShape = new ShapeDecorator(new Rectangle());
        System.out.println("Circle with normal border");
        circle.draw();

        System.out.println("\nCircle of red border");
        circleShape.draw();

        System.out.println("\nRectangle of red border");
        rectangleShape.draw();
    }
}
Circle with normal border
Shape: Circle

Circle of red border
Shape: Circle
Border Color: Red

Rectangle of red border
Shape: Rectangle
Border Color: Red

参考

代理模式

定义

实现

public interface Shape {
    void draw();
}
public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Shape: Circle");
    }
}
public class ProxyShape implements Shape {
     private Circle circle;
    
    @Override
    public void draw() {
        if(circle == null){
            circle = new Circle();
        }
        circle.draw();
    }
}
public class Test {
    public static void main(String[] args) {
        Shape shapeProxy = new ProxyShape();
        shape.draw();  
    }
}
Shape: Circle

参考

外观模式

定义

实现

public class CPU {
    public void startup(){
        System.out.println("cpu startup!");
    }

    public void shutdown(){
        System.out.println("cpu shutdown!");
    }
}
public class Memory {
    public void startup(){
        System.out.println("memory startup!");
    }
    
    public void shutdown(){
        System.out.println("memory shutdown!");
    }
}
public class Disk {
    public void startup(){
        System.out.println("disk startup!");
    }
    
    public void shutdown(){
        System.out.println("disk shutdown!");
    }
}
public class Computer {
    private CPU cpu;
    private Memory memory;
    private Disk disk;

    public Computer(){
        cpu = new CPU();
        memory = new Memory();
        disk = new Disk();
    }

    public void startup(){
        cpu.startup();
        memory.startup();
        disk.startup();
    }

    public void shutdown(){
        cpu.shutdown();
        memory.shutdown();
        disk.shutdown();
    }
}
public class Test {
    public static void main(String[] args) {
        Computer computer = new Computer();
        computer.startup();
        computer.shutdown();
    }
}
cpu startup!
memory startup!
disk startup!
    
cpu shutdown!
memory shutdown!
disk shutdown!

参考

桥接模式

定义

实现

public interface DrawAPI {
   public void drawCircle();
}
public class RedCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle, color: red);
   }
}
public class GreenCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle, color: green);
   }
}
public abstract class Shape {
    protected DrawAPI drawAPI;
    
    protected Shape(DrawAPI drawAPI){
        this.drawAPI = drawAPI;
    }
    
    public abstract void draw();  
}
public class Circle extends Shape {
    public Circle(DrawAPI drawAPI) {
        super(drawAPI);
    }

    public void draw() {
        drawAPI.drawCircle();
    }
}
public class BridgePatternDemo {
   public static void main(String[] args) {
      Shape redCircle = new Circle(new RedCircle());
      Shape greenCircle = new Circle(new GreenCircle());
 
      redCircle.draw();
      greenCircle.draw();
   }
}
Drawing Circle, color: red
Drawing Circle, color: green

参考

组合模式

定义

实现

public class Employee {
    private String name;
    private String dept;
    private int salary;
    private List<Employee> subordinates;

    //构造函数
    public Employee(String name,String dept, int sal) {
        this.name = name;
        this.dept = dept;
        this.salary = sal;
        subordinates = new ArrayList<Employee>();
    }

    public void add(Employee e) {
        subordinates.add(e);
    }

    public void remove(Employee e) {
        subordinates.remove(e);
    }

    public List<Employee> getSubordinates(){
        return subordinates;
    }

    public String toString(){
        return ("Employee :[ Name : "+ name 
                +", dept : "+ dept + ", salary :"
                + salary+" ]");
    }   
}
public class Test {
    public static void main(String[] args) {
        Employee CEO = new Employee("John","CEO", 30000);

        Employee headSales = new Employee("Robert","Head Sales", 20000);
        Employee salesExecutive1 = new Employee("Richard","Sales", 10000);

        CEO.add(headSales);
        headSales.add(salesExecutive1);

        //打印该组织的所有员工
        System.out.println(CEO); 
        for (Employee headEmployee : CEO.getSubordinates()) {
            System.out.println(headEmployee);
            for (Employee employee : headEmployee.getSubordinates()) {
                System.out.println(employee);
            }
        }        
    }
}
Employee :[ Name : John, dept : CEO, salary :30000 ]
Employee :[ Name : Robert, dept : Head Sales, salary :20000 ]
Employee :[ Name : Richard, dept : Sales, salary :10000 ]

参考

享元模式

定义

典型享元模式

class Flyweight {
    //内部状态innerState作为成员变量,同一个享元对象其内部状态是一致的
    private String innerState;
    public Flyweight(String innerState) {
        this.innerState = innerState;
    }
    //外部状态outerState在使用时由外部设置,不保存在享元对象中,即使是同一个对象
    public void operation(String outerState) {
        //......
    }
}
class FlyweightFactory {
    //定义一个HashMap用于存储享元对象,实现享元池
    private HashMap flyweights = newHashMap();
    
    public Flyweight getFlyweight(String key){
        //如果对象存在,则直接从享元池获取
        if(flyWeights.containsKey(key)){
            return (Flyweight) flyweights.get(key);
        } else {
            //如果对象不存在,先创建一个新的对象添加到享元池中,然后返回
            Flyweight fw = newConcreteFlyweight();
            flyweights.put(key,fw);
            return fw;
        }
    }
}

通用写法

/**
* 经典享元模式方法
* 场景:解决某些场景频繁生成实例问题;使用泛型,节省写判断逻辑
* 使用:String s = classicFlyweight(String.class);
*/
private Map<String, Object> flyweightMap;
private <T> T classicFlyweight(Class<T> clazz) {
    T t;

    if (flyweightMap == null)
        flyweightMap = new HashMap<>();
    String key = clazz.getName();
    if (flyweightMap.get(key) != null) {
        t = (T) flyweightMap.get(key);
    }else {
        try {
            t = clazz.newInstance();
            flyweightMap.put(key, t);
        } catch (Exception e) {
            t = null;
        }
    }

    return t;
}

连接池的实现

public class ConnectionPool {
    private Vector<Connection> pool;
    
    //公有属性
    private String url = "jdbc:mysql://localhost:3306/test";
    private String username = "root";
    private String password = "root";
    private String driverClassName = "com.mysql.jdbc.Driver";
 
    private int poolSize = 100;
    private static ConnectionPool instance = null;
    Connection conn = null;
 
    //构造方法,做一些初始化工作 
    private ConnectionPool() {
        pool = new Vector<Connection>(poolSize);
        for (int i = 0; i < poolSize; i++) {
            try {
                Class.forName(driverClassName);
                conn = DriverManager.getConnection(url, username, password);
                pool.add(conn);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
 
    //返回连接到连接池
    public synchronized void release() {
        pool.add(conn);
    }
 
    //返回连接池中的一个数据库连接
    public synchronized Connection getConnection() {
        if (pool.size() > 0) {
            Connection conn = pool.get(0);
            pool.remove(conn);
            return conn;
        } else {
            return null;
        }
    }
}

参考

行为型模式

思考

策略模式和状态模式

相同点

不同点

解释器模式

定义

实现

public interface Expression {
    public boolean interpret(String context);
}
public class TerminalExpression implements Expression {
    private String data;

    public TerminalExpression(String data){
        this.data = data; 
    }

    @Override
    public boolean interpret(String context) {
        if(context.contains(data)){
            return true;
        }
        return false;
    }
}
public class OrExpression implements Expression {
    private Expression expr1 = null;
    private Expression expr2 = null;

    public OrExpression(Expression expr1, Expression expr2) { 
        this.expr1 = expr1;
        this.expr2 = expr2;
    }

    @Override
    public boolean interpret(String context) {      
        return expr1.interpret(context) || expr2.interpret(context);
    }
}
public class AndExpression implements Expression {
    private Expression expr1 = null;
    private Expression expr2 = null;

    public AndExpression(Expression expr1, Expression expr2) { 
        this.expr1 = expr1;
        this.expr2 = expr2;
    }

    @Override
    public boolean interpret(String context) {      
        return expr1.interpret(context) && expr2.interpret(context);
    }
}
public class Test {
    //规则:Robert 和 John 是男性
    public static Expression getMaleExpression(){
        Expression robert = new TerminalExpression("Robert");
        Expression john = new TerminalExpression("John");
        return new OrExpression(robert, john);    
    }

    //规则:Julie 是一个已婚的女性
    public static Expression getMarriedWomanExpression(){
        Expression julie = new TerminalExpression("Julie");
        Expression married = new TerminalExpression("Married");
        return new AndExpression(julie, married);    
    }

    public static void main(String[] args) {
        Expression isMale = getMaleExpression();
        Expression isMarriedWoman = getMarriedWomanExpression();

        System.out.println("John is male? " + isMale.interpret("John"));
        System.out.println("Julie is a married women? " 
                           + isMarriedWoman.interpret("Married Julie"));
    }
}
John is male? true
Julie is a married women? true

参考

状态模式

定义

实现

public interface State {
    public void doAction(Context context);
}
public class StartState implements State {

    public void doAction(Context context) {
        System.out.println("Player is in start state");
        context.setState(this); 
    }

    public String toString(){
        return "Start State";
    }
}
public class StopState implements State {

    public void doAction(Context context) {
        System.out.println("Player is in stop state");
        context.setState(this); 
    }

    public String toString(){
        return "Stop State";
    }
}
public class Context {
    private State state;

    public Context(){
        state = null;
    }

    public void setState(State state){
        this.state = state;     
    }

    public State getState(){
        return state;
    }
}
public class StatePatternDemo {
    public static void main(String[] args) {
        Context context = new Context();

        StartState startState = new StartState();
        startState.doAction(context);

        System.out.println(context.getState().toString());

        StopState stopState = new StopState();
        stopState.doAction(context);

        System.out.println(context.getState().toString());
    }
}
Player is in start state
Start State
Player is in stop state
Stop State

参考

策略模式

定义

实现

public interface Strategy {
    int calculate(int a, int b);
}
// 加法算法
public class AddStrategy implements Strategy{
    @Override
    public int calculate(int a, int b) {
        return a + b;
    }
}
// 减法算法
public class SubtractStrategy implements Strategy{
    @Override
    public int calculate(int a, int b) {
        return a - b;
    }
}
public class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    // 动态替换算法(策略)
    public void replaceStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public int calculate(int a, int b) {
        return strategy.calculate(a, b);
    }
}
public class Test{
    public static void main(String[] args) {
        Strategy addStrategy = new AddStrategy();
        Context context = new Context(addStrategy);
        // 输出3
        System.out.println(context.calculate(1, 2));

        Strategy subStrategy = new SubtractStrategy();
        // 动态替换算法(策略)
        context.replaceStrategy(subStrategy);
        // 输出-1
        System.out.println(context.calculate(1, 2));
    }
}

参考

观察者模式

定义

实现

public interface Observer {
    //更新内容
    public void update(String msg);
}
public interface Subject {
    //添加观察者
    void attach(Observer observer);
    //删除观察者
    void detach(Observer observer);
    //通知更新
    void notify(String msg);
}
public class TestObserver implements Observer{
    private String info;

    public TestObserver(String info){
        this.info = info;
    }

    @Override
    public void update(String msg) {
        System.out.println(info + "----" + msg);
    }
}
public class TestSubject implements Subject{
    private List<Observer> mList = new ArrayList();
    
    @Override
    public void attach(Observer observer) {
        mList.add(observer);
    }
    
    @Override
    public void detach(Observer observer) {
        mList.remove(observer);
    }
    
    @Override
    public void notify(String msg) {
        for (Observer observer : mList) {
            observer.update(msg);
        }
    }
}
public class TestMain {
    public static void main(String[] args) {
        Subject subject = new TestSubject();

        Observer observerA = new TestObserver("A:");
        Observer observerB = new TestObserver("B:");
        subject.attach(observerA);
        subject.attach(observerB);
        subject.notify("通知One");
        subject.detach(observerA);
        subject.notify("通知Two");
    }
}
image.png

中介者模式

定义

实现

public class ChatRoom {
    public static void showMessage(User user, String message){
        System.out.println(new Date().toString()
                           + " [" + user.getName() +"] : " + message);
    }
}
public class User {
    private String name;

    public String getName() {
        return name;
    }

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

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

    public void sendMessage(String message){
        ChatRoom.showMessage(this,message);
    }
}
public class Test {
   public static void main(String[] args) {
      User robert = new User("Robert");
      User john = new User("John");
 
      robert.sendMessage("Hi! John!");
      john.sendMessage("Hello! Robert!");
   }
}
Thu Jan 31 16:05:46 IST 2013 [Robert] : Hi! John!
Thu Jan 31 16:05:46 IST 2013 [John] : Hello! Robert!

参考

备忘录模式

定义

实现

public class Original {
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Original(String value) {
        this.value = value;
    }

    public Memento createMemento(){
        return new Memento(value);
    }

    public void restoreMemento(Memento memento){
        this.value = memento.getValue();
    }
}
public class Memento {
    private String value;
 
    public Memento(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
 
    public void setValue(String value) {
        this.value = value;
    }
}
public class Storage {
    private Memento memento;
    
    public Storage(Memento memento) {
        this.memento = memento;
    }
 
    public Memento getMemento() {
        return memento;
    }
 
    public void setMemento(Memento memento) {
        this.memento = memento;
    }
}
public class Test {
    public static void main(String[] args) {
        // 创建原始类
        Original origi = new Original("egg");
        // 创建备忘录
        Storage storage = new Storage(origi.createMemento());

        // 修改原始类的状态
        System.out.println("初始化状态为:" + origi.getValue());
        origi.setValue("niu");
        System.out.println("修改后的状态为:" + origi.getValue());

        // 回复原始类的状态
        origi.restoreMemento(storage.getMemento());
        System.out.println("恢复后的状态为:" + origi.getValue());
    }
}
初始化状态为:egg
修改后的状态为:niu
恢复后的状态为:egg

参考

命令模式

定义

实现

public interface Order {
    void execute();
}
public class Stock {
   private String name = "ABC";
   private int quantity = 10;
 
   public void buy(){
      System.out.println("Stock [ Name: "+name+", 
         Quantity: " + quantity +" ] bought");
   }
}
public class BuyStock implements Order {
    private Stock abcStock;

    public BuyStock(Stock abcStock){
        this.abcStock = abcStock;
    }

    public void execute() {
        abcStock.buy();
    }
}
public class Broker {
    private List<Order> orderList = new ArrayList<Order>(); 

    public void takeOrder(Order order){
        orderList.add(order);      
    }

    public void placeOrders(){
        for (Order order : orderList) {
            order.execute();
        }
        orderList.clear();
    }
}
public class CommandPatternDemo {
    public static void main(String[] args) {
        Stock abcStock = new Stock();

        BuyStock buyStockOrder = new BuyStock(abcStock);
        Broker broker = new Broker();
        broker.takeOrder(buyStockOrder);

        broker.placeOrders();
    }
}
Stock [ Name: ABC, Quantity: 10 ] bought

参考

责任链模式

定义

实现

public abstract class AbstractLogger {
    public static int INFO = 1;
    public static int DEBUG = 2;
    public static int ERROR = 3;
    protected int level;

    //责任链中的下一个元素
    protected AbstractLogger nextLogger;

    public void setNextLogger(AbstractLogger nextLogger){
        this.nextLogger = nextLogger;
    }

    public void logMessage(int level, String message){
        if(this.level <= level){
            write(message);
        }
        if(nextLogger != null){
            nextLogger.logMessage(level, message);
        }
    }

    abstract protected void write(String message);
}
public class ConsoleLogger extends AbstractLogger {
    public ConsoleLogger(int level){
        this.level = level;
    }

    @Override
    protected void write(String message) {    
        System.out.println("Standard Console::Logger: " + message);
    }
}

public class ErrorLogger extends AbstractLogger {
    public ErrorLogger(int level){
        this.level = level;
    }

    @Override
    protected void write(String message) {    
        System.out.println("Error Console::Logger: " + message);
    }
}

public class FileLogger extends AbstractLogger {
    public FileLogger(int level){
        this.level = level;
    }

    @Override
    protected void write(String message) {    
        System.out.println("File::Logger: " + message);
    }
}
public class Test {
    private static AbstractLogger getChainOfLoggers(){
        AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);
        AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG);
        AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO);

        errorLogger.setNextLogger(fileLogger);
        fileLogger.setNextLogger(consoleLogger);
        return errorLogger;  
    }

    public static void main(String[] args) {
        AbstractLogger loggerChain = getChainOfLoggers();

        loggerChain.logMessage(AbstractLogger.INFO, "This is an information.");
        loggerChain.logMessage(AbstractLogger.DEBUG, "This is a debug level information.");
        loggerChain.logMessage(AbstractLogger.ERROR, "This is an error information.");
    }
}
Standard Console::Logger: This is an information.
File::Logger: This is a debug level information.
Standard Console::Logger: This is a debug level information.
Error Console::Logger: This is an error information.
File::Logger: This is an error information.
Standard Console::Logger: This is an error information.

参考

访问者模式

定义

实现

public interface Visitor {
    public void visit(Subject sub);
}
public class MyVisitor implements Visitor {
    @Override
    public void visit(Subject sub) {
        System.out.println("visit the subject:"+sub.getSubject());
    }
}
public interface Visitor {
    public void visit(Subject sub);
}
public class MyVisitor implements Visitor {
    @Override
    public void visit(Subject sub) {
        System.out.println("visit the subject:"+sub.getSubject());
    }
}
public interface Subject {
    public void accept(Visitor visitor);
    public String getSubject();
}
public class MySubject implements Subject {
    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }

    @Override
    public String getSubject() {
        return "love";
    }
}
public class Test {
    public static void main(String[] args) {
        Visitor visitor = new MyVisitor();
        Subject sub = new MySubject();
        sub.accept(visitor);    
    }
}

参考

迭代器模式

定义

实现

public interface Iterator {
    public boolean hasNext();
    public Object next();
}
public interface Container {
    public Iterator getIterator();
}
public class NameRepository implements Container {
    public String names[] = {"Robert" , "John" ,"Julie" , "Lora"};

    @Override
    public Iterator getIterator() {
        return new NameIterator();
    }

    private class NameIterator implements Iterator {

        int index;

        @Override
        public boolean hasNext() {
            if(index < names.length){
                return true;
            }
            return false;
        }

        @Override
        public Object next() {
            if(this.hasNext()){
                return names[index++];
            }
            return null;
        }     
    }
}
public class Test {
    public static void main(String[] args) {
        NameRepository namesRepository = new NameRepository();
        for(Iterator iter = namesRepository.getIterator(); iter.hasNext();){
            String name = (String)iter.next();
            System.out.println("Name : " + name);
        }  
    }
}
Name : Robert
Name : John
Name : Julie
Name : Lora

参考

模板模式

定义

实现

public abstract class Game {
    abstract void initialize();
    abstract void startPlay();
    abstract void endPlay();

    //模板
    public final void play(){
        //初始化游戏
        initialize();
        //开始游戏
        startPlay();
        //结束游戏
        endPlay();
    }
}
public class Football extends Game {
    @Override
    void endPlay() {
        System.out.println("Football Game Finished!");
    }

    @Override
    void initialize() {
        System.out.println("Football Game Initialized! Start playing.");
    }

    @Override
    void startPlay() {
        System.out.println("Football Game Started. Enjoy the game!");
    }
}
public class Test {
    public static void main(String[] args) {
        Game game = new Football();
        game.play();      
    }
}
Football Game Initialized! Start playing.
Football Game Started. Enjoy the game!
Football Game Finished!

参考

最后

上一篇 下一篇

猜你喜欢

热点阅读