Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

再談設計模式:以咖啡店計價模型為例

編輯:關於 Android 程式設計

有句話說得好:設計模式沒有好壞之分,只有合適與否。

日前去面試很有意思,技術考官指著最後一道二選一的編程題說,那是昨晚專門為我新加的。聽完我既感動又慚愧,當場在紙上寫了大概思路,為了不辜負考官的重視,回家後又在電腦上把它完整實現了一遍。

題目大意是:一家咖啡店賣摩卡、布列夫、拿鐵等多種咖啡,每杯咖啡可以搭配方糖、鮮奶、奶油、鹽等配料,請設計一個能計算「咖啡+配料」單價的模型。

一、抽象基類 Coffee

我抽象出一個咖啡基類 Coffee,摩卡、布列夫、拿鐵都繼承它。這個類包含:不含配料的咖啡單價 price、用來存放配料的容器 ecoratorRelishChain,以及計算總價的 getTotalPrices 方法。

// 咖啡抽象基類
@interface Coffee : NSObject
@property (nonatomic, strong) DecoratorChain *ecoratorRelishChain; // 調味盒
@property (nonatomic, strong) NSDecimalNumber *price;             // 不含配料單價
- (NSDecimalNumber *)getTotalPrices;                                // 取得總價
@end

@implementation Coffee
- (id)init {
    self = [super init];
    if (self) {
        _coffeeName = @"咖啡名稱";
        price = [[NSDecimalNumber alloc] initWithString:@"20"];
    }
    return self;
}
- (NSDecimalNumber *)getTotalPrices {
    return [self.price decimalNumberByAdding:[ecoratorRelishChain getCountPrice]];
}
@end

二、配料抽象類 EcoratorRelish

EcoratorRelish 是方糖、奶油、牛奶、鹽等配料的抽象類,繼承自 UIButton,點擊時會自動把自己加入調味盒(chain)。它包含自身單價 price 與可覆寫的優惠策略 configPrivilege。

@interface EcoratorRelish : UIButton
@property (nonatomic, strong) NSDecimalNumber *price; // 單價
- (void)configPrivilege;      // 可覆寫:配置優惠策略
- (DecoratorChain *)getComponentCoffee;
@end

@implementation EcoratorRelish
- (id)init {
    self = [super init];
    if (self) {
        [self addTarget:self action:@selector(addDecoratorChain)
       forControlEvents:UIControlEventTouchUpInside];
    }
    return self;
}
// 找到所屬的 ViewController,進而取得咖啡的調味盒
- (UIViewController *)getViewController {
    Class vcc = [UIViewController class];
    UIResponder *responder = self;
    while ((responder = [responder nextResponder]))
        if ([responder isKindOfClass:vcc])
            return (UIViewController *)responder;
    return nil;
}
- (DecoratorChain *)getEcoratorRelishChain {
    return [self getViewController].coffee.ecoratorRelishChain;
}
- (void)addDecoratorChain {
    [[self getEcoratorRelishChain] addDecoratorRelish:self];
}
@end

三、調味盒 DecoratorChain

DecoratorChain 用來保存所有已加入的配料,並能統計總價:

@interface DecoratorChain : NSMutableArray
- (void)addDecoratorRelish:(EcoratorRelish *)ecoratorRelish;
@end

@implementation DecoratorChain
- (void)addDecoratorRelish:(EcoratorRelish *)ecoratorRelish {
    [self addObject:ecoratorRelish];
}
- (NSDecimalNumber *)getCountPrice {
    for (EcoratorRelish *tmp in self) {
        [_countPrice decimalNumberByAdding:tmp.price];
    }
    return _countPrice;
}
@end

小結

回頭看這個設計,最明顯用到的就是裝飾模式(Decorator)與組合模式(Composite),再搭配策略模式處理優惠。三個角色各司其職,擴充配料時不必更動既有程式碼,正是設計模式帶來的彈性所在。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved