大话设计模式(java实现)

来源:互联网 发布:内外网切换软件下载 编辑:程序博客网 时间:2024/06/13 21:33
 //策略模式
//它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响使用算法的用户。
abstract class CashSuper
{
 public abstract double acceptCash(double money);
}
class CashNormal extends CashSuper
{
 public double acceptCash(double money)
 {
  return money;
 }
}
class CashRebate extends CashSuper
{
 private double moneyRebate=0.0;
 public void setRebate(double moneyRebate)
 {
  this.moneyRebate=moneyRebate;
 }
 public double acceptCash(double money)
 {
  return moneyRebate*money;
 }
}
class CashReturn extends CashSuper
{
 private double moneyCondition;
 private double moneyReturn;
 public void setReturn(double moneyCondition,double moneyReturn)
 {
  this.moneyCondition=moneyCondition;
  this.moneyReturn=moneyReturn;
 }
 public double acceptCash(double money)
 {
  double result=money;
  if(money>=moneyCondition)
  {
   result=money-(money/moneyCondition)*moneyReturn;
  }
  return result;
 }
}
class CashFactory
{
 public static CashSuper createCashAccept(char i)
 {
  CashSuper cs=null;
  switch(i)
  {
   case '1':
   {
    cs=new CashNormal();
    break;
   }
   case '2':
   {
    cs=new CashReturn();
    break;
   }
   case '3':
   {
    cs=new CashRebate();
    break;
   }
  }
  return cs;
 }
}
public class Demo02
{
 public static void main(String argc[])
 {
  CashSuper cs1=CashFactory.createCashAccept('1');
  double totalPrice=cs1.acceptCash(500.0);
  System.out.println("totalPrice="+totalPrice);
 }
}