原型模式

Posted 仙人掌的刺

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原型模式相关的知识,希望对你有一定的参考价值。

大概是java版本升级了,clone方法不严格写好像也没什么问题。

/**
 * Created by hero on 16-4-2.
 */
public class Company implements Cloneable {
    private String name;

    public String getName() {
        return name;
    }

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

    public Company(String name) {
        this.name = name;
    }

    public Company clone() {
        Company company = null;
        try {
            company = (Company) super.clone();
        } catch (CloneNotSupportedException e) {
        }
        return company;
    }
}
/**
 * Created by hero on 16-4-2.
 */
public class BusinessCard implements Cloneable {
    private String name;
    private Company company;

    public String getName() {
        return name;
    }

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

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

    public BusinessCard clone() {
        BusinessCard card = null;
        try {
            card = (BusinessCard) super.clone();
            if(company!= null){
                card.company = company.clone();
            }
        } catch (CloneNotSupportedException e) {
        } //won‘t happen
        return card;
    }
}
public class Main {

    public static void main(String[] args) {
        BusinessCard card = new BusinessCard();
        card.setName("张无忌");
        card.setCompany(new Company("武当"));
        BusinessCard card1 = card.clone();
        card1.setCompany(new Company("少林"));
        System.out.println(card.getName() + ", " + card.getCompany().getName());
        System.out.println(card1.getName() + ", " + card1.getCompany().getName());
    }
}

 

以上是关于原型模式的主要内容,如果未能解决你的问题,请参考以下文章

设计模式之原型模式(Prototype)详解及代码示例

设计模式课程 设计模式精讲 9-2 原型模式coding

设计模式--原型模式

5.原型模式

设计模式原型模式

csharp 设计模式 - 原型 - 结构代码