原型模式_通过复制生成实例(避免实例重复创建从而减少内存消耗)
@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设计模式案例
引用该文档请注明出处
原文:https://www.cnblogs.com/imaikce/p/10903157.html