原型模式_通過複製生成實例(避免實例重覆創建從而減少記憶體消耗) 閱讀前準備 1、淺克隆(shallow clone),淺拷貝是指拷貝對象時僅僅拷貝對象本身和對象中的基本變數,而不拷貝對象包含的引用指向的對象。(如:對象A1中包含對B1的引用,B1中包含對C1的引用。淺拷貝A1得到A2,A2中依然包含 ...
原型模式_通過複製生成實例(避免實例重覆創建從而減少記憶體消耗)
閱讀前準備
- 1、淺克隆(shallow clone),淺拷貝是指拷貝對象時僅僅拷貝對象本身和對象中的基本變數,而不拷貝對象包含的引用指向的對象。
(如:對象A1中包含對B1的引用,B1中包含對C1的引用。淺拷貝A1得到A2,A2中依然包含對B1的引用,
B1中依然包含對C1的引用。深拷貝則是對淺拷貝的遞歸,深拷貝A1得到A2,A2中包含對B2(B1的copy)的引用,B2中包含對C2(C1的copy)的引用) - 2、深克隆(deep clone),深拷貝不僅拷貝對象本身,而且拷貝對象包含的引用指向的所有對象
(需要重寫clone方法.如@Override protected Object clone() throws CloneNotSupportedException { Husband husband = (Husband) super.clone(); husband.wife = (Wife) husband.getWife().clone(); return husband; } )
/** * 產品生成管理器 * @author maikec * @date 2019/5/11 */ public final class ProductManager { private final Map<String, Product> productMap = Collections.synchronizedMap(new HashMap<>( )); public void register(Product product){ productMap.put( product.getClass().getSimpleName(),product ); } public Product create(Product product){ Product result = productMap.get( product.getClass().getSimpleName() ); if(null == result){ register( product ); result = productMap.get( product.getClass().getSimpleName() ); } return result.createClone(); } } /** * 原型類 * @author maikec * @date 2019/5/11 */ public interface Product extends Cloneable { void use(); /** * 克隆 * @return */ Product createClone(); } /** * @author maikec * @date 2019/5/11 */ public class CloneFailureException extends RuntimeException { public CloneFailureException(){ super("clone failure"); } public CloneFailureException(String msg){ super(msg); } } /** * @author maikec * @date 2019/5/11 */ public class MessageProduct implements Product { @Override public void use() { System.out.println( "MessageProduct" ); } @Override public MessageProduct createClone() { try { return (MessageProduct) clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); throw new CloneFailureException( ); } } } /** * @author maikec * @date 2019/5/11 */ public class UnderlineProduct implements Product { @Override public void use() { System.out.println( "UnderlineProduct" ); } @Override public UnderlineProduct createClone() { try { return (UnderlineProduct) clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); throw new CloneFailureException(); } } } /** * @author maikec * @date 2019/5/11 */ public class PrototypeDemo { public static void main(String[] args) { ProductManager manager = new ProductManager(); manager.register( new UnderlineProduct() ); manager.register( new MessageProduct() ); manager.create( new UnderlineProduct() ).use(); manager.create( new MessageProduct() ).use(); } }
附錄
github.com/maikec/patt… 個人GitHub設計模式案例
聲明
引用該文檔請註明出處