简单工厂模式:只是用来解决创建对象的问题;每个对象都有共同的行为(方法),但是具体的实现不同;
需求如下:给一商场做一个结算软件,这个结算总共包括“正常收费”,“满300减100”,“打八折”几项;这个例子就能使用简单工厂模式;
1.首先将共同的行为抽象出来:接收一个没有活动的支付额,返回一个参与活动后的支付额
package com.zcbl.client.zcblsdk.factorymodel;
/**
* Created by serenitynanian on 2018/2/2.
*/
public abstract class CashSuper {
public abstract double acceptCash(double money);
}
2.分别创建“正常收费”,“满300减100”,“打八折”这三个活动的类;
package com.zcbl.client.zcblsdk.factorymodel.impl;
import com.zcbl.client.zcblsdk.factorymodel.CashSuper;
/**
* Created by serenitynanian on 2018/2/2.
* 正常收费
*/
public class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
package com.zcbl.client.zcblsdk.factorymodel.impl;
import com.zcbl.client.zcblsdk.factorymodel.CashSuper;
/**
* Created by serenitynanian on 2018/2/2.
* 现金折扣
*/
public class CashRebate extends CashSuper {
private double moneyRebate ;
public CashRebate(double moneyRebate) {
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money*this.moneyRebate;
}
}
package com.zcbl.client.zcblsdk.factorymodel.impl;
import com.zcbl.client.zcblsdk.factorymodel.CashSuper;
/**
* Created by serenitynanian on 2018/2/2.
* 返利收费子类
*/
public class CashReturn extends CashSuper {
private double moneyCondition ;
private double moneyReturn ;
public CashReturn(double moneyCondition, double moneyReturn) {
this.moneyCondition = moneyCondition;
this.moneyReturn = moneyReturn;
}
@Override
public double acceptCash(double money) {
double result = money ;
if (money > moneyCondition) {
result = money - (money/moneyCondition)*moneyReturn;
}
return result;
}
}
3.创建现金收费工厂类,来根据传入的活动类型来创建相应的实例;
package com.zcbl.client.zcblsdk.factorymodel;
import com.zcbl.client.zcblsdk.factorymodel.impl.CashNormal;
import com.zcbl.client.zcblsdk.factorymodel.impl.CashRebate;
import com.zcbl.client.zcblsdk.factorymodel.impl.CashReturn;
/**
* Created by serenitynanian on 2018/2/2.
* 简单工厂模式:这个模式只是用来解决创建对象的问题;
* 现金收费工厂类
*/
public class CashFactory {
public static CashSuper createCashAccept(String type){
CashSuper cs = null ;
switch (type) {
case "正常收费":
cs = new CashNormal();
break ;
case "满300减100":
cs = new CashReturn(300, 100);
break ;
case "打八折":
cs = new CashRebate(0.8);
break ;
}
return cs ;
}
public static void main(String[] args) {
CashSuper cs = CashFactory.createCashAccept("打八折");
double result = cs.acceptCash(100);
System.out.println("----result----->"+result);
}
}
网友评论