一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第3天,点击查看活动详情。
上一篇文章介绍了设计模式的七大原则,感兴趣的同学请移步设计模式(一):初识设计模式
设计模式类型
根据设计模式的参考书中文译名为《设计模式-可复用的面向对象软件元素》中所提到的,总共有23种设计模式,它们提供了软件开发过程中面临的一般问题的最佳解决方案,根据用法分为三大类:创建型模式(Creational Patterns)、结构型模式(Structural Patterns)和行为型模式(Behavioral Patterns)。
创建型模式
这些设计模式提供了一种创建对象的方式,并且可以隐藏创建逻辑,即对外暴露接口,封装实现细节,不是直接使用new运算符直接实例化对象。
- 单例模式(Singleton Pattern)
- 工厂模式(Factory Pattern)
- 抽象工厂模式(Abstract Factory Pattern)
- 建造者模式(Builder Pattern)
- 原型模式(Prototype Pattern)
结构型模式
结构型模式是处理类和对象的组合,关注类和对象如何更好地组装起来。
- 适配器模式(Adapter Pattern)
- 桥接模式(Bridge Pattern)
- 组合模式(Composite Pattern)
- 装饰器模式(Decorator Pattern)
- 外观模式(Facade Pattern)
- 享元模式(Flyweight Pattern)
- 代理模式(Proxy Pattern)
行为型模式
行为型模式涉及到算法和对象间的职责分配,关注对象之间的通信模式。
- 责任链模式(Chain of Responsibility Pattern)
- 命令模式(Command Pattern)
- 解释器模式(Interpreter Pattern)
- 迭代器模式(Iterator Pattern)
- 中介者模式(Mediator Pattern)
- 备忘录模式(Memento Pattern)
- 观察者模式(Observer Pattern)
- 状态模式(State Pattern)
- 策略模式(Strategy Pattern)
- 模板模式(Template Pattern)
- 访问者模式(Visitor Pattern)
创建型模式
单例模式
类的单例模式就是采取一定的方法保证在整个的软件系统中,对某个类只能存在一个对象实例,并且该类只提供一个取得其对象实例的方法。优点是能节省系统资源,常用于需要频繁的进行创建和销毁的对象、创建对象时耗时过多和消耗资源过多。
1.饿汉式(静态常量)
代码实现:
class Singleton {
private Singleton(){}
private final static Singleton instance = new Singleton();
public static Singleton getInstance(){
return instance;
}
}
优点写法简单,在类装载时完成实例化,避免线程同步的问题
缺点不能达到懒加载的效果,如果这个实例未被使用则会造成内存资源的浪费
2.懒汉式(线程不安全)
class Singleton {
private Singleton(){}
private static Singleton instance;
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
优点起到了懒加载的效果
缺点只能在单线程环境中使用,假如在多线程环境下,一个线程进入了if(singleton == null)判断语句块,还未往下执行时,另一个线程也通过了这个判断语句,便会产生多个实例
3.懒汉式(线程安全,同步方法)
class Singleton {
private static Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
优点线程安全
缺点每个线程在想获取类的实例时,执行getInstance()方法都需要进行同步,效率低
4.双重检查
class Singleton {
private static volatile Singleton instance;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(instance == null){
synchronized (Singleton.class){
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
优点线程安全,延迟加载,效率较高
5.静态内部类
class Singleton {
private Singleton(){}
private static class SingletonInstance{
private static final Singleton INSTANCE = new Singleton();
}
public static synchronized Singleton getInstance(){
return SingletonInstance.INSTANCE;
}
}
采用了类加载的机制来保证初始化实例时只有一个线程
优点线程安全,延迟加载,效率高
6.枚举
enum Singleton {
INSTANCE;
}
优点能避免多线程同步和反序列化重新创建新的对象