編輯:關於 Android 程式設計
有句話說得好:設計模式沒有好壞之分,只有合適與否。
日前去面試很有意思,技術考官指著最後一道二選一的編程題說,那是昨晚專門為我新加的。聽完我既感動又慚愧,當場在紙上寫了大概思路,為了不辜負考官的重視,回家後又在電腦上把它完整實現了一遍。
題目大意是:一家咖啡店賣摩卡、布列夫、拿鐵等多種咖啡,每杯咖啡可以搭配方糖、鮮奶、奶油、鹽等配料,請設計一個能計算「咖啡+配料」單價的模型。
我抽象出一個咖啡基類 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 是方糖、奶油、牛奶、鹽等配料的抽象類,繼承自 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 用來保存所有已加入的配料,並能統計總價:
@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),再搭配策略模式處理優惠。三個角色各司其職,擴充配料時不必更動既有程式碼,正是設計模式帶來的彈性所在。
Handler 消息機制完全解析(二):MessageQueue 的隊列管理
關於這個隊列,先說明一點:它的實現既非 Collection 的子類,亦非 Map 的子類,而是 Message 本身。因為 Message 本身就是鏈結串列節點。隊列中
Android ROM 解包打包全流程:ext4 鏡像處理與批處理腳本自動化定製
eMMC 是手機、平板等裝置常見的嵌入式儲存方案,因為封裝內已整合控制器、提供標準介面並自行管理閃存,越來越受 Android 手機廠商青睞。以 eMMC 為儲存裝置
Android 菜單的三種實現方式:Options Menu、Context Menu 與 Submenu
菜單是許多應用不可或缺的一部分,Android 更是如此——幾乎所有 Android 設備都有一個「menu」鍵。SDK 提供了三種類型:options menu(常規菜
Android 插件化實作:用 DexClassLoader 與 AssetManager 啟動插件 Activity
在 Android 應用中,並非所有功能都必須預先安裝。透過動態載入外掛 APK 或 ZIP 檔,可以在不安裝系統應用程式的情況下擴充主程式能力。這篇文章說明如何以 De