我已经上传到gitee上了,里面有注释,每一种我都写了代码,写了注释,基本上很容易理解。
链接:
https://gitee.com/hhp123/design-mode.git
我写的8种设计模式分别是:
比如原型模式的深拷贝:
package 原型模式.深拷贝.字节流对象流; import java.io.*; public class Sheep implements Cloneable { String name; Sheep friends; // 深拷贝:也为引用类型分配存储空间 public Sheep(String name) { this.name = name; } @Override protected Object clone() { try { ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(this); ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi = new ObjectInputStream(bi); Object clone = oi.readObject(); return clone; } catch (Exception e) { e.printStackTrace(); return null; } } public static void main(String[] args) { Sheep sheep1 = new Sheep("第一只羊"); Sheep sheep2 = new Sheep("第二只羊"); sheep1.friends = sheep2; System.out.println(sheep1.friends == sheep2);// true } }
其他模式在gitee看吧~
对你有帮助不忘记点赞,收藏,后面会继续更新!~