大话设计模式(1) --- 简单工厂模式|策略模式
2020-01-12 本文已影响0人
官子寒
1. 简单工厂模式
简单工厂模式主要用来解决创建实例的问题

public abstract class CashSuper {
public abstract int acceptCash(int money);
}
public class CashNormal extends CashSuper {
@Override
public int acceptCash(int money) {
return money;
}
}
public class CashRebate extends CashSuper {
private int moneyRate = 0;
public CashRebate(int moneyRate) {
this.moneyRate = moneyRate;
}
@Override
public int acceptCash(int money) {
return money * this.moneyRate;
}
}
public class CashFactory {
public static CashSuper getCash(int cashOption) {
CashSuper cashSuper = null;
switch (cashOption) {
case 1 :
cashSuper = new CashNormal();
break;
case 2 :
cashSuper = new CashRebate(2);
break;
default:
break;
}
return cashSuper;
}
}
public class CashClient {
public static void main(String[] args) throws InterruptedException {
System.out.println("请选择结算方式:");
System.out.println("1 --- 原价");
System.out.println("2 --- 2倍的价格");
CashSuper cashSuper = null;
Scanner scanner = new Scanner(System.in);
switch(scanner.next()) {
case "1" :
cashSuper = CashFactory.getCash(1);
System.out.println(cashSuper.acceptCash(100));
break;
case "2" :
cashSuper = CashFactory.getCash(2);
System.out.println(cashSuper.acceptCash(100));
break;
}
}
}

2. 策略模式
策略模式是一种定义一系列算法的方法,从概念上来讲,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法与使用算法类之间的耦合

public class Context {
private CashSuper cashSuper;
public Context (CashSuper cashSuper) {
this.cashSuper = cashSuper;
}
public int acceptCash(int money) {
return cashSuper.acceptCash(money);
}
}
public class ContextTest {
public static void main(String[] args) {
Context context = new Context(new CashRebate(3));
System.out.println(context.acceptCash(200));
}
}
- 策略模式的
Strategy
类层次为Context
定义了一系列的可供重用的算法或行为,继承有助于析取出这些算法的公共功能 - 策略模式还有助于简化单元测试,因为每个算法都有自己的类,可以通过自己的接口单独编程
- 单纯用策略模式,需要在客户端进行
switch
或if
判断来创建实例
3. 策略和简单工厂模式结合
- 将客户端中创建实例的
switch
部分收到Context
中
public class Context_Factory {
private CashSuper cashSuper;
public Context_Factory (int strategyOption) {
switch (strategyOption) {
case 1:
cashSuper = new CashNormal();
break;
case 2:
cashSuper = new CashRebate(2);
break;
}
}
public int acceptCash(int money) {
return cashSuper.acceptCash(money);
}
}
public class Context_Factory_Test {
public static void main(String[] args) {
Context_Factory context_factory;
Scanner scanner = new Scanner(System.in);
switch(scanner.next()) {
case "1" :
context_factory = new Context_Factory(1);
System.out.println(context_factory.acceptCash(200));
break;
case "2" :
context_factory = new Context_Factory(2);
System.out.println(context_factory.acceptCash(200));
break;
}
}
}