实现策略模式和模板方法模式示例,添加支付策略和烹饪流程,增强代码可读性
This commit is contained in:
parent
5fbbada4b7
commit
e5be1b62c2
|
|
@ -0,0 +1,51 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
/*
|
||||
实例:
|
||||
汤宝宝成为了收银员,消费者可以使用现金或者支付宝支付。
|
||||
*/
|
||||
|
||||
type Strategy interface {
|
||||
Pay(amount float64) string
|
||||
}
|
||||
|
||||
type CashPayment struct{}
|
||||
|
||||
func (c *CashPayment) Pay(amount float64) string {
|
||||
return fmt.Sprintf("使用现金支付了 %.2f 元", amount)
|
||||
}
|
||||
|
||||
type AlipayPayment struct{}
|
||||
|
||||
func (a *AlipayPayment) Pay(amount float64) string {
|
||||
return fmt.Sprintf("使用支付宝支付了 %.2f 元", amount)
|
||||
}
|
||||
|
||||
type Context struct {
|
||||
strategy Strategy
|
||||
}
|
||||
|
||||
func (c *Context) SetStrategy(strategy Strategy) {
|
||||
c.strategy = strategy
|
||||
}
|
||||
|
||||
func (c *Context) Pay(amount float64) string {
|
||||
return c.strategy.Pay(amount)
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("=========== 策略模式 ===========")
|
||||
|
||||
context := &Context{}
|
||||
|
||||
context.SetStrategy(&CashPayment{})
|
||||
fmt.Println(context.Pay(100))
|
||||
|
||||
context.SetStrategy(&AlipayPayment{})
|
||||
fmt.Println(context.Pay(200))
|
||||
|
||||
fmt.Println()
|
||||
fmt.Println("========= 策略模式结束 =========")
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
/*
|
||||
实例:
|
||||
汤宝宝炒西红柿鸡蛋。
|
||||
*/
|
||||
|
||||
// 抽象接口
|
||||
type Dish interface {
|
||||
PrepareIngredients()
|
||||
Cook()
|
||||
Serve()
|
||||
}
|
||||
|
||||
// 模板方法
|
||||
func DoCooking(dish Dish) {
|
||||
fmt.Print("第一步:")
|
||||
dish.PrepareIngredients()
|
||||
fmt.Print("第二步:")
|
||||
dish.Cook()
|
||||
fmt.Print("第三步:")
|
||||
dish.Serve()
|
||||
}
|
||||
|
||||
// 具体实现
|
||||
type TomatoEggDish struct{}
|
||||
|
||||
func (t *TomatoEggDish) PrepareIngredients() {
|
||||
fmt.Println("准备西红柿和鸡蛋;")
|
||||
}
|
||||
|
||||
func (t *TomatoEggDish) Cook() {
|
||||
fmt.Println("炒西红柿和鸡蛋;")
|
||||
}
|
||||
|
||||
func (t *TomatoEggDish) Serve() {
|
||||
fmt.Println("装盘,西红柿鸡蛋炒好了。")
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("========== 模板方法模式 ==========")
|
||||
dish := &TomatoEggDish{}
|
||||
DoCooking(dish)
|
||||
fmt.Println()
|
||||
fmt.Println("======== 模板方法模式结束 ========")
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
"""
|
||||
实例:
|
||||
汤宝宝成为了收银员,消费者可以使用现金或者支付宝支付。
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class Strategy(ABC):
|
||||
@abstractmethod
|
||||
def pay(self, amount: float) -> str:
|
||||
pass
|
||||
|
||||
|
||||
class CashPayment(Strategy):
|
||||
def pay(self, amount: float) -> str:
|
||||
return(f"使用现金支付了 {amount:.2f} 元。")
|
||||
|
||||
|
||||
class AlipayPayment(Strategy):
|
||||
def pay(self, amount: float) -> str:
|
||||
return(f"使用支付宝支付了 {amount:.2f} 元。")
|
||||
|
||||
|
||||
class Context:
|
||||
strategy: Strategy
|
||||
|
||||
def set_strategy(self, strategy: Strategy) -> None:
|
||||
self._strategy = strategy
|
||||
|
||||
def pay(self, amount: float) -> str:
|
||||
return self._strategy.pay(amount)
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("=========== 策略模式 ===========")
|
||||
|
||||
context = Context()
|
||||
context.set_strategy(CashPayment())
|
||||
print(context.pay(100.0))
|
||||
context.set_strategy(AlipayPayment())
|
||||
print(context.pay(200.0))
|
||||
|
||||
print("\n========= 策略模式结束 =========")
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
"""
|
||||
实例:
|
||||
汤宝宝炒西红柿鸡蛋。
|
||||
"""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
||||
class Dish(ABC):
|
||||
@abstractmethod
|
||||
def prepare_ingredients(self):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def cook(self):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def serve(self):
|
||||
pass
|
||||
|
||||
def do_cooking(self):
|
||||
print("第一步:", end="")
|
||||
self.prepare_ingredients()
|
||||
print("第二步:", end="")
|
||||
self.cook()
|
||||
print("第三步:", end="")
|
||||
self.serve()
|
||||
|
||||
class TomatoEggDish(Dish):
|
||||
def prepare_ingredients(self):
|
||||
print("准备西红柿和鸡蛋。")
|
||||
|
||||
def cook(self):
|
||||
print("炒西红柿和鸡蛋。")
|
||||
|
||||
def serve(self):
|
||||
print("装盘,西红柿鸡蛋炒好了。")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("========== 模板方法模式 ==========")
|
||||
dish = TomatoEggDish()
|
||||
dish.do_cooking()
|
||||
print("\n======== 模板方法模式结束 ========")
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
/*
|
||||
实例:
|
||||
汤宝宝成为了收银员,消费者可以使用现金或者支付宝支付。
|
||||
*/
|
||||
|
||||
interface Strategy {
|
||||
pay(amount: number): string;
|
||||
}
|
||||
|
||||
class CashStrategy implements Strategy {
|
||||
pay(amount: number): string {
|
||||
return `使用现金支付了${amount.toFixed(2)}元`;
|
||||
}
|
||||
}
|
||||
|
||||
class AlipayStrategy implements Strategy {
|
||||
pay(amount: number): string {
|
||||
return `使用支付宝支付了${amount.toFixed(2)}元`;
|
||||
}
|
||||
}
|
||||
|
||||
class Context {
|
||||
private strategy: Strategy| null = null;
|
||||
|
||||
setStrategy(strategy: Strategy) {
|
||||
this.strategy = strategy;
|
||||
}
|
||||
|
||||
pay(amount: number): string {
|
||||
if (!this.strategy) {
|
||||
throw new Error("支付策略未设置");
|
||||
}
|
||||
return this.strategy.pay(amount);
|
||||
}
|
||||
}
|
||||
|
||||
(function(){
|
||||
console.log("=========== 策略模式 ===========")
|
||||
const context = new Context();
|
||||
|
||||
context.setStrategy(new CashStrategy());
|
||||
console.log(context.pay(100));
|
||||
|
||||
context.setStrategy(new AlipayStrategy());
|
||||
console.log(context.pay(200));
|
||||
|
||||
console.log("\n========= 策略模式结束 =========")
|
||||
})()
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
/*
|
||||
实例:
|
||||
汤宝宝炒西红柿鸡蛋。
|
||||
*/
|
||||
|
||||
abstract class Dish {
|
||||
abstract prepareIngredients(): string;
|
||||
abstract cook(): string;
|
||||
abstract serve(): string;
|
||||
doCooking(): void {
|
||||
console.log("第一步:", this.prepareIngredients());
|
||||
console.log("第二步:", this.cook());
|
||||
console.log("第三步:", this.serve());
|
||||
}
|
||||
}
|
||||
|
||||
class TomatoEggs extends Dish {
|
||||
prepareIngredients(): string {
|
||||
return "准备西红柿和鸡蛋;";
|
||||
}
|
||||
cook(): string {
|
||||
return "炒西红柿和鸡蛋;";
|
||||
}
|
||||
serve(): string {
|
||||
return "装盘,西红柿鸡蛋炒好了。";
|
||||
}
|
||||
}
|
||||
|
||||
(function(){
|
||||
console.log("========== 模板方法模式 ==========");
|
||||
const dish = new TomatoEggs();
|
||||
dish.doCooking();
|
||||
console.log("\n======== 模板方法模式结束 ========");
|
||||
})()
|
||||
Loading…
Reference in New Issue