常见的设计模式

152 阅读2分钟

设计模式的原则

单一职责

里氏替换

依赖倒置

接口隔离

迪米特法则

开闭原则

设计模式的分类

创建型

创建型模式是用来创建对象的模式,抽象了实例化的过程,帮助一个系统独立于其关联对象的创建、组合和表示方式。

单例模式

饿汉模式

public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton(){
    }
    public static Singleton getInstance(){
        return instance;
    }
}

懒汉

public class Singleton {
    private static Singleton instance;
    private Singleton(){
    }
    public static Singleton getInstance(){
        if(instance == null){
            instance = new Singleton();
        }
        return instance;
    }
}

线程安全(DCL)

//volatile的作用:防止指令重排序
public class Singleton {
    private static volatile Singleton instance;
    private Singleton(){
    }
    public static Singleton getInstance(){
        if(instance == null){
            synchronized (Singleton.class) {
                instance = new Singleton();
            }
        }
        return instance;
    }
}

线程安全(类加载)

//依赖类加载时线程安全的<clinit>方法初始化
public class Singleton { 
    private Singleton(){
    }
    public static Singleton getInstance(){  
        return Inner.instance;  
    }  
    private static class Inner {  
        private static final Singleton instance = new Singleton();  
    }  
} 

线程安全(类加载)

enum Singleton2  {
    INSTANCE;
    Singleton2(){
    }
    public static Singleton2 getInstance() {
        return Singleton2.INSTANCE;
    }
}

工厂模式

简单工厂

产品接口
interface product{
    String name();
}
产品1
class product1 implements product{

    @Override
    public String name() {
        return "product1";
    }
}
产品2
class product2 implements product{

    @Override
    public String name() {
        return "product2";
    }
}
//简单工厂实例
class FirstFacory {
    public product create(int type) {
        switch (type) {
            case 1:
                return new product1();
            default:
                return new product2();
        }
    }
}

//工厂方法接口
public interface Factory {
    product create();
}

//一级工厂
class firstFacory implements Factory{
    @Override
    public product create() {
        return new product1();
    }
}

抽象工厂

建造者模式

原型模式

结构型

采用继承机制来组合接口或实现(类结构型模式),或者通过组合一些对象实现新的功能(对象结构型模式)。

代理模式

装饰模式

适配器模式

组合模式

桥梁模式

外观模式

享元模式

行为型

行为型设计模式关注的是对象的行为,用来解决对象之间的联系问题。

模板方法

命令模式

责任链模式

策略模式

迭代器模式

中介者模式

观察者模式

备忘录模式

访问者模式

状态模式

解释器模式