一、创建型
1、简单工厂模式

1)定义抽象类
java
/**
* <p>
* 抽象类
* </p>
*
* @author fcy
* @since 2025-08-18
*/
public abstract class CashSuper {
abstract double acceptCash(double money);
}
2)无折扣实现类
java
/**
* <p>
* 不打折正常类
* </p>
*
* @author fcy
* @since 2025-08-18
*/
public class CashNormal extends CashSuper{
@Override
double acceptCash(double money) {
return money;
}
}
3)打折实现类
java
/**
* <p>
* 折扣类
* </p>
*
* @author fcy
* @since 2025-08-18
*/
public class CashRebate extends CashSuper{
private double rebate = 1d;
public CashRebate(double rebate) {
this.rebate = rebate;
}
@Override
double acceptCash(double money) {
return money * rebate;
}
}
4)满减实现类
java
/**
* <p>
* 满减类 满多少返多少
* </p>
*
* @author fcy
* @since 2025-08-18
*/
public class CashReturn extends CashSuper{
private double moneyCondition = 0.0d;
private double moneyReturn = 0.0d;
public CashReturn(double moneyCondition, double moneyReturn) {
this.moneyCondition = moneyCondition;
this.moneyReturn = moneyReturn;
}
@Override
double acceptCash(double money) {
double result = money;
if (money > moneyCondition) {
result = money - Math.floor(money / moneyCondition) * moneyReturn;
}
return result;
}
}
5)定义工厂类
java
/**
* <p>
* 工厂类
* </p>
*
* @author fcy
* @since 2025-08-18
*/
public class CashFactory {
public static CashSuper createCashAdapter(String type) {
return switch(type) {
case "正常收费" -> new CashNormal();
case "满300减30" -> new CashReturn(300,30);
case "打八折" -> new CashRebate(0.8);
default -> throw new RuntimeException();
};
}
}
6)测试类
java
public class Test {
public static void main(String[] args) {
CashFactory cashFactory = new CashFactory();
CashSuper cashSuper = cashFactory.createCashAdapter("满300减30");
CashSuper cashSuper1 = cashFactory.createCashAdapter("打八折");
double cost = cashSuper.acceptCash(700);
double cost1 = cashSuper1.acceptCash(200);
System.out.println(cost);
System.out.println(cost1);
}
}
二、结构型
三、行为型
1、策略模式

1)使用简单工厂模式的类
2)创建上下文类
java
/**
* <p>
* 上下文类
* </p>
*
* @author fcy
* @since 2025-08-19
*/
public class CashContext {
private CashSuper cs;
public CashContext(String type) {
this.cs = switch(type) {
case "正常收费" -> new CashNormal();
case "满300减30" -> new CashReturn(300,30);
case "打八折" -> new CashRebate(0.8);
default -> throw new RuntimeException();
};
}
public double getResult(double money) {
return cs.acceptCash(money);
}
}
3)测试类
java
public class Test {
public static void main(String[] args) {
double cost = new CashContext("打八折").getResult(700);
double cost1 = new CashContext("满300减30").getResult(200);
System.out.println(cost);
System.out.println(cost1);
}
}