设计模式-原型模式思考

设计模式-原型模式思考

简单例子

我需要创建一个人,这个人除了Id不同,其他都一样。

package mode.prototype;
/**
 * @author gang.tu
 */
public class Body {
    Body(String name) {
        this.name = name;
    }

    private String name;

    public String getName() {
        return name;
    }
}
package mode.prototype;

/**
 * @author gang.tu
 */
public class Head {
    Head(String name) {
        this.name = name;
    }
    private String name;

    public String getName() {
        return name;
    }
}
package mode.prototype;
/**
 * @author gang.tu
 */
public class Person implements Cloneable {
    private String id;
    private Body body;
    private Head head;

    @Override
    public Person clone() {
        Person person = null;
        try {
            person = (Person) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return person;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Body getBody() {
        return body;
    }

    public void setBody(Body body) {
        this.body = body;
    }

    public Head getHead() {
        return head;
    }

    public void setHead(Head head) {
        this.head = head;
    }
}

单元测试

package mode.prototype;

import org.junit.Test;

import static org.junit.Assert.*;

public class PersonTest {

    @Test
    public void test() {
        Body body = new Body("body");
        Head head = new Head("head");
        Person person = new Person();
        person.setBody(body);
        person.setHead(head);
        person.setId("1");
        System.out.println(person.getId());
        System.out.println(person.getBody().getName());
        System.out.println(person.getHead().getName());
        Person person1 = person.clone();
        person1.setId("2");
        System.out.println(person1.getId());
        System.out.println(person1.getBody().getName());
        System.out.println(person1.getHead().getName());
    }
}

运行结果:

1
body
head
2
body
head

总结

  • 原型模式主要关键词:实现Cloneable接口,实现clone方法。
  • 实现clone方法为浅拷贝。
  • 当构建一个对象非常复杂时或者创建成本非常高时可以使用。
  • clone不会运行构造方法。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值