`
897371388
  • 浏览: 526626 次
文章分类
社区版块
存档分类
最新评论

prototype(原型设计模式)

 
阅读更多

1、原始模型设计模式 通过给出一个原始对象来指明要创建的对象的类型,然后用复制这个对象的原型来创建更多的同类型的对象,缺点是每一个需要被复制的类都必须提供一个克隆的方法,克隆还分深度克隆和浅克隆。

2、uml图如下


3、java代码如下

public class Manager {
private Hashtable<String, Product> hashtables = new Hashtable<String, Product>();


public void register(String productName, Product product) {
hashtables.put(productName, product);
}


public Product createClone(String productName) {
Product product = hashtables.get(productName);
return product.createClone();
}
}



public interface Product extends Cloneable{
public void use();
public Product createClone();
}



public class MessageBox implements Product{


public Product createClone() {
try {
return (Product) this.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}


public void use() {
System.out.println("********");
}


}



public class UnderLinePen implements Product{


public Product createClone() {
try {
return (Product) this.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}


public void use() {
System.out.println("____________");
}


}


public class Main {
public static void main(String[] args) {
Manager manager = new Manager();
Product p1 = new UnderLinePen();
Product p2 = new MessageBox();

manager.register("p1", p1);
manager.register("p2", p2);

manager.createClone("p1").use();
manager.createClone("p2").use();
}
}



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics