android应用开发设计模式之原型模式

原型模式:用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。
新建赛车的接口:

public interface car_interface {
 	public void start();
 	public void stop();
}

新建宝马汽车的实现类:

public class bmw_impl implements car_interface, Cloneable {
	private car_tyre car_tyre_ref;
	private bmw_impl bmw;
	public void start() {

	}

	public void stop() {

	}

	public car_tyre getCar_tyre_ref() {
		return car_tyre_ref;
	}

	public void setCar_tyre_ref(car_tyre car_tyre_ref) {
		this.car_tyre_ref = car_tyre_ref;
	}

	@Override 
	public Object clone()throws CloneNotSupportedException {
		super.clone();
		bmw = new bmw_impl();
		bmw.setCar_tyre_ref(new car_tyre());

		return bmw;
	}

}

新建宝马的配件轮胎类在宝马汽车实现类中需要注意的是将原来protected类型的clone方法要变成public,这样才可以对外公开,可以被调用,将秘密公开化。

public class car_tyre {

	private String name ="德国制造原版轮胎";

	public String getName() {
		return name;
	}
}

新建android客户端,给出xml以及activity:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent" 
	android:orientation="vertical" > 

	<TextView 
		android:id="@+id/textview01" 
		android:layout_width="fill_parent" 
		android:layout_height="wrap_content" /> 
	<TextView 
		android:id="@+id/textview02" 
		android:layout_width="fill_parent" 
		android:layout_height="wrap_content" /> 
	<TextView 
		android:id="@+id/textview03" 
		android:layout_width="fill_parent" 
		android:layout_height="wrap_content" /> 
	<TextView 
		android:id="@+id/textview04" 
		android:layout_width="fill_parent" 
		android:layout_height="wrap_content" /> 
</LinearLayout>

下面是activity

public class PrototypeActivityextends Activity {
    	private bmw_impl bmw1;
	private bmw_impl bmw2;
	private TextView textview01;
	private TextView textview02;
	private TextView textview03;
	private TextView textview04;

	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			textview01= (TextView)findViewById(R.id.textview01);
			textview02=(TextView)findViewById(R.id.textview02);
			textview03= (TextView)findViewById(R.id.textview03);
			textview04=(TextView)findViewById(R.id.textview04);
			bmw1 = new bmw_impl();
			bmw1.setCar_tyre_ref(new car_tyre());
			textview01.setText("我的宝马参数是:" + bmw1);
			textview02.setText("我的宝马的轮胎参数是:" + bmw1.getCar_tyre_ref());
			bmw2 = (bmw_impl) bmw1.clone();
			textview03.setText("他人的宝马的参数是:" + bmw2);
			textview04.setText("他人的宝马的参数是:" + bmw2);
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}

	}

}

下面是效果图:

 

源代码下载地址:http://download.csdn.net/detail/jindegegesun/4087689

source link:http://blog.csdn.net/jindegegesun/article/details/7291207

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值