本文内容来自《Head First Design Pattern》以及老师英文PPT(基本上也是来自这本书),有错误欢迎指正!
The Singleton Pattern单例模式
单例模式确保一个类只有一个实例(instance),并提供一个全局实例访问该实力的点(provides a global point of access to that instance)。
public class Singleton {
private static (synchronized) Singleton uniqueInstance;
// …
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// …
}
线程不安全
通过通过添加synchronized关键字,我们迫使每个线程在进入该方法之前等待轮到它。也就是说,方法中不能同时存在两个线程。
但是这样不是最优解,因为synchronized很昂贵,。。。
Use eager instantiation(即时实例化) instead of lazy instantiation(延迟实例化)
Double Checked Looking
public class Singleton {
private volatile static Singleton uniqueInstance;
//volatile关键字确保在将唯一实例初始化为Singleton实例时,多个线程正确地处理该实例
private Singleton () {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
//Check for an instance; if there isn’t one, enter the synchronized block
synchronized (Singleton.class) {
//Once in the block, check again and if still null, create an instance
if (uniqueInstance == null) {uniqueInstance = new Singleton();}
}
}
return uniqueInstance;
}
}
The Command Pattern
命令模式将请求封装为对象,从而允许您用不同的请求、队列或日志请求参数化其他对象,并支持可撤销的操作。
- Invoker:setCommand是把具体的Command绑定在这个类的Command对象上
- undo通过在Receiver存LastCommand来实现。并且在每个Command具体类写相反的方法(实现undo)。
The Adapter Pattern
适配器模式将类的接口转换为client期望的另一个接口。适配器允许类一起工作,否则由于不兼容的接口而无法一起工作。
The Facade Pattern外观模式
外观模式为子系统中的一组接口提供了统一的接口;定义了一个更高级的接口,使子系统更易于使用。
(此例子来源网络,侵删致歉!)
电脑整机是 CPU、内存、硬盘的外观。有了外观以后,启动电脑和关闭电脑都简化了。
直接 new 一个电脑。
在 new 电脑的同时把 cpu、内存、硬盘都初始化好并且接好线。
对外暴露方法(启动电脑,关闭电脑)。
启动电脑(按一下电源键):启动CPU、启动内存、启动硬盘
关闭电脑(按一下电源键):关闭硬盘、关闭内存、关闭CPU