Java原型模式

优点:

  • 性能优良
  • 逃避构造函数的约束

缺点:

  • 由于使用原型模式复制对象时不会调用类的构造方法,所以原型模式无法和单例模式组合使用,因为原型类需要将clone方法的作用域修改为public类型,那么单例模式的条件就无法满足了。
  • 对象不能声明为final

应用场景:

  • 资源优化场景
  • 性能和安全要求的场景

注意:

  • (拷贝 int ,long,char等) (不拷贝 String,内部数组,引用对象)

/**
 * 原型模式
 * 
 * @(拷贝 int ,long,char等) (不拷贝 String,内部数组,引用对象)
 * @ final与clone()方法互斥
 * 
 * @author Administrator
 *
 */
public class Brother implements Cloneable {
	/**
	 * 姓名
	 */
	private String name;
	/**
	 * 年龄
	 */
	private int age;

	public String getName() {
		return name;
	}

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

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	/**
	 * 
	 */
	public void exect() {

		System.out.println("姓名:" + getName() + " 年龄=" + getAge());
	}

	private ArrayList<String> mData = new ArrayList<>();

	public void setValue(String value) {
		mData.add(value);
	}

	public ArrayList<String> getValue() {
		return mData;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Brother clone() {
		// TODO Auto-generated method stub
		Brother object = null;
		try {
			object = (Brother) super.clone();
//			object.mData = (ArrayList<String>) this.mData.clone(); //深拷贝
		} catch (CloneNotSupportedException e) {
			// TODO: handle exception
			System.out.println(e);
		}

		return object;
	}

}

调用

		// 原型模式
		Brother brother = new Brother();
		brother.setValue("哥哥");
		Brother brother1 = brother.clone();
		brother1.setValue("弟弟");
		System.out.println("list = "+brother.getValue());
		System.out.println("list = "+brother1.getValue());
//输出结果  浅拷贝
list = [哥哥, 弟弟]
list = [哥哥, 弟弟]
//输出结果  深拷贝
list = [哥哥]
list = [哥哥, 弟弟]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值