设计模式专题
创建型模式
1.单例模式
-
保证一个类只有实例,并且提供一个访问该实例的全局访问点
-
饿汉式 static变量会在类装载时初始化,无并发;
public class test { private static /*final*/test s=new test(); private test() {} public static /*synchronized*/ test getInstance() { return s; } }
-
懒汉式 延迟加载,每次调用getInstance()都要同步,并发,效率低
public class test { private static test s; private test() {} public static synchronized test getInstance() { if(s==null) { s=new test(); } return s; } }
-
双重检测锁
public class test { private static test instance=null; public static test getInstance() { if (instance==null) {//创建一次后instance不为空 test t; synchronized (test.class) { t=instance; if(t==null) { System.out.println(test.class); if(t==null) { t=new test(); } } } instance=t; } return instance; } private test() {} }
-
静态内部类实现单例
-
线程安全、调用效率高、懒加载
public class test { private static class testInstance { private static test s=new test(); } public static test getInstance() { return testInstance.s; } private test() {} }
-
-
使用枚举实现单例
-
无延迟加载效果
public enum test { INSTTANCE; private void testOperation() { } }
-
-
单例只能创建出一个对象,可通过如下方式破解单例(E:\JAVA\JAVA\葵花宝典\设计模式.249)破解及防止破解代码-------有空再过一次
- 反射调用私有构造器
- 反序列化方式构造多个对象
2.工厂模式
- 简单工厂模式
-
工厂方法模式
- 解决简单工厂模式不完全满足OCP原则,不修改已有类的前提下增加新的工厂实现类;
-
简单工厂模式和方法工厂模式PK
- 结构复杂度
- 代码复杂度
- 客户端编程难度
- 管理上的难度
-
方法工厂模式优势,但在实际生产中使用简单工厂模式
-
抽象工厂模式
3.建造者模式
- 实现构建和装备的解耦
- Airship只是起一个指挥者的作用,通知builder造部件,通过Director组合部件后将对象返还给Airship
4.原型模式(克隆)
- 浅克隆:复制引用对象地址,克隆前后的变量指向同一引用对象
- 深克隆:连同引用对象一起拷贝,在类里重写clone方法,将引用对象的属性也进行clone
- 使用序列化和反序列化的方式实现深克隆
Date d= new Date();
Student2 s1=new Student2("张三", d);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(baos);
oos.writeObject(s1);
byte[] data=baos.toByteArray();
ByteArrayInputStream bais=new ByteArrayInputStream(data);
ObjectInputStream ois =new ObjectInputStream(bais);
Student2 s2=(Student2) ois.readObject();