【23种设计模式】之原型模式

39 阅读1分钟

本文已参与[新人创作礼]活动,一起开启掘金创作之路。

说明

  • 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

角色

  • 原型角色(ps,也可以搞成两个,如抽象原型角色以及各个具体实现原型角色)

代码实现

  • 即通过clone方法来实现对象的克隆
public class Product implements Cloneable{
    private String name ;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public Product clone(){
        Product product = null;
        try{
            product = (Product)super.clone();
        }catch (Exception e){

        }
        return product;
    }
}
public class Client {
    public static void  main(String[] args){
        Product product = new Product();
        Thread thread = new Thread(){
            @Override
            public void run(){
                Product clone = product.clone();
                Random random = new Random();
                clone.setName(random.nextLong()+"");
                clone.setAge(random.nextInt());
                System.out.println(Thread.currentThread().getName()+":"+clone.getName()+","+clone.getAge());
            }
        };
        Thread[] threads = new Thread[100];
        for(int i=0;i<threads.length;i++){
            threads[i] = new Thread(thread);
            threads[i].start();
        }
    }
}