Kaynağa Gözat

模板方法模式下单

code_hero 2 hafta önce
ebeveyn
işleme
68a388f3ae

+ 11 - 0
src/main/java/templateMethodPattern/main.java

@@ -0,0 +1,11 @@
+package templateMethodPattern;
+
+import responsibilityPattern.entity.Order;
+import templateMethodPattern.template.impl.NormalOrder;
+
+public class main {
+    public static void main(String[] args) {
+        NormalOrder normalOrder = new NormalOrder();
+        normalOrder.processOrder(new Order("1",100D,10));
+    }
+}

+ 35 - 0
src/main/java/templateMethodPattern/template/OrderProcessTemplate.java

@@ -0,0 +1,35 @@
+package templateMethodPattern.template;
+
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import responsibilityPattern.entity.Order;
+
+public abstract class OrderProcessTemplate {
+    private static final Logger log = LoggerFactory.getLogger(OrderProcessTemplate.class);
+
+    public final void processOrder(Order order) {
+        validateOrder(order);
+        needCoupon(order);
+        applyCoupon(order);
+        calculatePrice(order);
+        saveOrder(order);
+    }
+    //检查订单,子类必须重写
+     public abstract void validateOrder(Order order);
+    //计算价格
+     public abstract void calculatePrice(Order order);
+    //是否需要优惠券
+     boolean needCoupon(Order order) {
+        return false;
+    }
+    //使用优惠券
+     void applyCoupon(Order order) {
+        log.info("default applyCoupon");
+    }
+     void saveOrder(Order order) {
+        log.info("default saveOrder");
+    }
+
+
+}

+ 21 - 0
src/main/java/templateMethodPattern/template/impl/NormalOrder.java

@@ -0,0 +1,21 @@
+package templateMethodPattern.template.impl;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import responsibilityPattern.entity.Order;
+import templateMethodPattern.template.OrderProcessTemplate;
+
+public class NormalOrder extends OrderProcessTemplate {
+    private static final Logger log = LoggerFactory.getLogger(NormalOrder.class);
+
+
+    @Override
+    public void validateOrder(Order order) {
+        log.info("normalOrder validateOrder");
+    }
+
+    @Override
+    public void calculatePrice(Order order) {
+        log.info("normalOrder calculatePrice");
+    }
+}

+ 20 - 0
src/main/java/templateMethodPattern/template/impl/SeckillOrder.java

@@ -0,0 +1,20 @@
+package templateMethodPattern.template.impl;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import responsibilityPattern.entity.Order;
+import templateMethodPattern.template.OrderProcessTemplate;
+
+public class SeckillOrder extends OrderProcessTemplate {
+    private static final Logger log = LoggerFactory.getLogger(SeckillOrder.class);
+
+    @Override
+    public void validateOrder(Order order) {
+        log.info("seckillOrder validateOrder");
+    }
+
+    @Override
+    public void calculatePrice(Order order) {
+        log.info("seckillOrder calculatePrice");
+    }
+}