示例一:
@Data // 注解方式生成get set 方法
abstract class Operation { // 抽象类 ,继承使用方法和字段
private Double numberA;
private Double numberB;
public Double getResult(){
return 0D;
}
}
public class Add extends Operation { // 加法运算类
public Double getResult(){
return getNumberA() + getNumberB(); // 获取父类属性进行运算
}
}
public class Subtraction extends Operation{ // 减法运算类
public Double getResult(){
return getNumberA() - getNumberB();
}
}
public class OperationFactory { // 调用类
public static void main(String[] args) {
String operator = "+";
Operation add = createOperator(operator); // 多态
add.setNumberA(10D);
add.setNumberB(10D);
System.out.println(add.getResult());
}
// 不适用if else原因:switch case会生成一个跳转表来指示实际的case分支的地址,而if…else却需要遍历条件分支直到命中条件, 效率switch更高,时间换空间
private static Operation createOperator(String operator){ // 匹配算数运算符
Operation operation = null;
switch (operator){
case "+":
operation = new Add();
break;
case "-":
operation = new Subtraction();
break;
default:
System.out.println("输入有误");
}
return operation;
}
}
示例二:
package com.mybatis.designpatterns.simplefactory.cash;
public class Cash {
/**
* 收银系统:
* 需求:1.客户买卖东西正常收费
* 2.打折收费
* 3.返利
* @param args
*/
public static void main(String[] args) {
String type = "正常收费";
String type2 = "打折";
String type3 = "促销";
CashSuper cash = cash(type2);
System.out.println(cash.acceptCash(1000D));
}
private static CashSuper cash(String type){
CashSuper cashSuper = null;
switch (type){
case "正常收费":
cashSuper = new CashNormal();
break;
case "打折":
cashSuper = new CashDiscount(0.8);
break;
case "促销":
cashSuper = new CashPromotion(300D,100D);
break;
default:
System.out.println("输入有误");
}
return cashSuper;
}
}
package com.mybatis.designpatterns.simplefactory.cash;
/**
* 收费超类
*/
abstract class CashSuper {
public abstract Double acceptCash(Double money);
}
package com.mybatis.designpatterns.simplefactory.cash;
/**
* 促销
*/
public class CashPromotion extends CashSuper{
private Double promotionPrivate; // 促销价格
private Double promotionRebate; // 返利
public CashPromotion(Double promotionPrivate, Double promotionRebate) {
this.promotionPrivate = promotionPrivate;
this.promotionRebate = promotionRebate;
}
@Override
public Double acceptCash(Double money) {
if (money >= promotionPrivate){
return money - money / promotionPrivate * promotionRebate;
}
return money; // 收原价
}
}
package com.mybatis.designpatterns.simplefactory.cash;
/**
*
*原价
*
*/
public class CashNormal extends CashSuper {
@Override
public Double acceptCash(Double money) {
return money;
}
}
package com.mybatis.designpatterns.simplefactory.cash;
/**
* 打折
*/
public class CashDiscount extends CashSuper{
private Double discount = 1D; //默认不打折
public CashDiscount(Double discount) {
this.discount = discount;
}
@Override
public Double acceptCash(Double money){
return money * discount;
}
}
感受:需掌握和灵活运用继承及多态知识,代码量感觉多了很多,真鸡儿麻烦.