《Head First设计模式》要点(四)
OO原则:(未完。。。)
封装变化
多用组合,少用继承
针对接口编程,不针对实现编程
为交互对象之间的松耦合设计而努力
对扩展开放,对修改关闭
依赖抽象,不要依赖具体类
OO模式:
单件模式:确保只有一个实例,并提供全局访问点。
要点:
·确保一个雷最多只有一个实例
·提供这个实例的全局访问点
·java中实现一个单件模式需要一个private constructor,一个static function,一个static instance varible
·如果使用多个类加载器,可能导致多个单件失效而产生多个实例
注意:
单件模式在多线程情况下容易出现问题,可能产生不止一个实例
解决方案有如下三种:
1.同步getInstance()方法
public class Singleton { private static Singleton uniqueInstance; private Singleton(){} public static synchronized Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; }
2.装载类时直接初始化
public class Singleton { private static Singleton uniqueInstance = new Singleton(); private Singleton(){} public static synchronized Singleton getInstance() { return uniqueInstance; }
3.双重检查加锁,减少同步
public class Singleton { private volatile static Singleton uniqueInstance; private Singleton(){} public static Singleton getInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; }
第一个方法效率比较低,第三个方法不适用于1.4以前的版本。