设计模式-策略模式

策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。

MainActivity.java

package com.cdh.strategymode;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
/**
 * 
 * @Description:策略模式,关键在于CashContext.java
 * @author:cdh
 * @time:2014年12月12日 上午11:09:20
 */
public class MainActivity extends Activity {
	private List<String> caculateList;
	private List<ListMode> caculist;
	private ListView lv;
	Spinner sp;
	ArrayAdapter<String> adapter;
	MyAdapter madp;
	EditText singleprice, thingsnum;
	Button surebtn, rewritebtn;
	int spos;
	String strsNum,strsPrice;
	Double sResult;//同种物品*同种物品的数量
	int sNum;//物品数量
	Double sPrice;//物品价格
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initWidget();
		
		sp.setAdapter(adapter);// 通过setAdapter()来读取ArrayAdapter里的数据
		sp.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				spos = position;
				
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
	}

	private void initWidget() {

		caculateList = new ArrayList<String>();// spinner
		caculateList.add("正常收费");
		caculateList.add("0.8");
		caculateList.add("满500送100");
		

		caculist = new ArrayList<ListMode>();

		sp = (Spinner) findViewById(R.id.Spinner01);
		adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, caculateList);
		lv = (ListView) findViewById(R.id.lv);
		madp = new MyAdapter(getBaseContext(), caculist);
		lv.setAdapter(madp);
		singleprice = (EditText) findViewById(R.id.singleprice);
		thingsnum = (EditText) findViewById(R.id.thingsnum);
		surebtn = (Button) findViewById(R.id.surebtn);
		surebtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				strsNum=thingsnum.getText().toString();
				strsPrice=singleprice.getText().toString();
				sPrice=Double.parseDouble(strsPrice);
				sNum=Integer.parseInt(strsNum);
				/**
				 * 只需单价和数量,选择促销类型,丢给CashContext类处理,得到顾客需付金额
				 */
				CashContext cc=new CashContext(spos);
				sResult=cc.getResult(sPrice*sNum);
				
				ListMode mode = new ListMode();
				mode.setSingleprice(strsPrice);
				mode.setThingsnum(strsNum);
				mode.setCaculateway(caculateList.get(spos));
				mode.setsResult(sResult);
				caculist.add(mode);

				madp.notifyDataSetChanged();

			}
		});

	}

}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.cdh.strategymode.MainActivity" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp" >

        <EditText
            android:id="@+id/singleprice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
                android:inputType="number"
            android:hint="请输入单价" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        
            android:text="单价" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="10dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="数量" />

        <EditText
            android:id="@+id/thingsnum"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
             android:inputType="number"
            android:hint="请输入商品数量" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="10dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="计算方式" />

        <Spinner
            android:id="@+id/Spinner01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal"
        android:padding="10dp" >

        <Button
            android:id="@+id/surebtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="确定" />

        <Button
            android:id="@+id/rewritebtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/surebtn"
            android:text="重置" />
    </RelativeLayout>
    <ListView
        android:id="@+id/lv"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

</LinearLayout>
CashContext.java
package com.cdh.strategymode;

/**
 * 
 * @Description:精髓所在,构造方法中与工厂模式相结合
 * @author:cdh
 * @time:2014年12月12日 上午11:19:38
 */
public class CashContext {
	CashSuper cs;

	public CashContext(int whichCash) {
		// TODO Auto-generated constructor stub
		/*
		 * 根据商家选择的促销类型,返回促销对象
		 */
		cs=CreateFactory.createCash(whichCash);
		
	}
/**
 * 
 * @param money 客户应付的钱
 * @return 客户实际需要付的钱
 */
	public double getResult(double money) {
		return cs.acceptCash(money);
	}
	
}
CashSuper.java
package com.cdh.strategymode;

abstract class CashSuper {
public abstract double acceptCash(double money);
}
CashNormal.java
<pre class="java" name="code">package com.cdh.strategymode;
/**
 * 
 * @Description:正常收费
 * @author:cdh
 * @time:2014年12月12日 上午10:34:29
 */
public class CashNomal extends CashSuper{
	@Override
	public double acceptCash(double money) {
		// TODO Auto-generated method stub
		return money;
	}

}

CashRebate.java
 
<pre class="java" name="code">package com.cdh.strategymode;
/**
 * 
 * @Description:打折
 * @author:cdh
 * @time:2014年12月12日 上午10:48:05
 */
public class CashRebate extends CashSuper {
	private double rebate;

	public CashRebate(double rebate) {
		// TODO Auto-generated constructor stub
		this.rebate = rebate;
	}

	@Override
	public double acceptCash(double money) {
		// TODO Auto-generated method stub
		double result = 0;
		result = money * rebate;
		return result;
	}

}

CashRetrun.java
 
<pre class="java" name="code"><pre class="java" name="code">package com.cdh.strategymode;
/**
 * 
 * @Description:满几送几
 * @author:cdh
 * @time:2014年12月12日 上午10:43:36
 */
public class CashReturn extends CashSuper {
	private double moneyCondition = 0.0d;
	private double moneyReturn = 0.0d;

	public CashReturn(double moneyCondition, double moneyReturn) {
		// TODO Auto-generated constructor stub
		this.moneyCondition = moneyCondition;
		this.moneyReturn = moneyReturn;
	}

	@Override
	public double acceptCash(double money) {
		// TODO Auto-generated method stub
		double result = 0;
		if (money >= moneyCondition) {
			result = money - Math.floor(money / moneyCondition) * moneyReturn;
		}
		return result;
	}

}

MyAdapter.java
 
<pre class="java" name="code">package com.cdh.strategymode;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {
	private LayoutInflater layoutInflater;
	List<ListMode> caculist;

	public MyAdapter(Context context, List<ListMode> caculist) {
		this.caculist = caculist;
		layoutInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return caculist.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return caculist.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = layoutInflater.inflate(R.layout.lvitem, null);
			holder.sigprice = (TextView) convertView
					.findViewById(R.id.sigprice);
			holder.num = (TextView) convertView.findViewById(R.id.num);
			holder.caculway = (TextView) convertView
					.findViewById(R.id.caculway);
			holder.sResult=(TextView)convertView.findViewById(R.id.singletotalprice);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.sigprice.setText(caculist.get(position).getSingleprice());
		holder.num.setText(caculist.get(position).getThingsnum());
		holder.caculway.setText(caculist.get(position).getCaculateway());
		holder.sResult.setText(caculist.get(position).getsResult()+"");
		return convertView;
	}

	class ViewHolder {
		public TextView sigprice, num, caculway,sResult;
	}

}

ListMode.java
 
<pre class="java" name="code">package com.cdh.strategymode;

public class ListMode {
	private String singleprice;
	private String thingsnum;
	private String caculateway;
	private Double sResult;
	
	
	public Double getsResult() {
		return sResult;
	}
	public void setsResult(Double sResult) {
		this.sResult = sResult;
	}
	public String getSingleprice() {
		return singleprice;
	}
	public void setSingleprice(String singleprice) {
		this.singleprice = singleprice;
	}
	public String getThingsnum() {
		return thingsnum;
	}
	public void setThingsnum(String thingsnum) {
		this.thingsnum = thingsnum;
	}
	public String getCaculateway() {
		return caculateway;
	}
	public void setCaculateway(String caculateway) {
		this.caculateway = caculateway;
	}
}

lvitem.xml
 
<pre class="html" name="code"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="单价"/>
     <TextView
         android:id="@+id/sigprice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0.0"/>
 <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" 数量"/>
     <TextView
         android:id="@+id/num"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0.0"/>
     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" 计算方式"/>
     <TextView
         android:id="@+id/caculway"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0.0"/>
       <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" 合计"/>
     <TextView
         android:id="@+id/singletotalprice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0.0"/>
</LinearLayout>

 
package com.cdh.strategymode;
/**
 * 
 * @Description:满几送几
 * @author:cdh
 * @time:2014年12月12日 上午10:43:36
 */
public class CashReturn extends CashSuper {
	private double moneyCondition = 0.0d;
	private double moneyReturn = 0.0d;

	public CashReturn(double moneyCondition, double moneyReturn) {
		// TODO Auto-generated constructor stub
		this.moneyCondition = moneyCondition;
		this.moneyReturn = moneyReturn;
	}

	@Override
	public double acceptCash(double money) {
		// TODO Auto-generated method stub
		double result = 0;
		if (money >= moneyCondition) {
			result = money - Math.floor(money / moneyCondition) * moneyReturn;
		}
		return result;
	}

}

 
<p>package com.cdh.strategymode;
/**
 * 
 * @Description:正常收费
 * @author:cdh
 * @time:2014年12月12日 上午10:34:29
 */
public class CashNomal extends CashSuper{
 @Override
 public double acceptCash(double money) {
  // TODO Auto-generated method stub
  return money;
 }</p><p>}
</p>CashNomal
<pre class="java" name="code">package com.cdh.strategymode;

abstract class CashSuper {
public abstract double acceptCash(double money);
}


CreateFactory.java

package com.cdh.strategymode;
/**
 * 
 * @Description:返回促销对象,若商场需求改变,比如,打折数改变,满几送几改变,只需要修改这个类即可,
 * 实现低耦合,高内聚
 * @author:cdh
 * @time:2014年12月12日 上午11:36:57
 */
public class CreateFactory {
	private static double rebate=0.8;//打几折
	private static int overMoney=500,giveMoney=100;//满几送几
	public static CashSuper createCash(int which) {
		CashSuper cs=null;
		switch (which) {
		case 0:
			CashNomal cn = new CashNomal();
			cs = cn;
			break;
		case 1:
			CashRebate cr = new CashRebate(rebate);
			cs = cr;
			break;
		case 2:
			CashReturn ct = new CashReturn(overMoney, giveMoney);
			cs = ct;
			break;

		default:
			break;
		}

		return cs;

	}
}


 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值