tailieunhanh - Pro JavaScript Design Patterns 2008 phần 5

và cuối cùng đi lên với một lớp học có thể tái sử dụng có thể được sử dụng để kiểm tra các đối tượng cho các phương pháp cần thiết. và sẽ thay đổi từ một người sử dụng tiếp theo. Hình 9-2 cho thấy một ví dụ điển hình. Một xác nhận chức năng đó là hợp chặt chẽ với các lĩnh vực hình thức cụ thể, | 98 CHAPTER 7 THE FACTORY PATTERN bicycle Bicycle return bicycle GeneralProductsBicycleShop class. var GeneralProductsBicycleShop function extend GeneralProductsBicycleShop BicycleShop function model var bicycle switch model case The Speedster bicycle new GeneralProductsSpeedster break case The Lowrider bicycle new GeneralProductsLowrider break case The Flatlander bicycle new GeneralProductsFlatlander break case The Comfort Cruiser default bicycle new GeneralProductsComfortCruiser bicycle Bicycle return bicycle All of the objects created from these factory methods respond to the Bicycle interface so any code written can treat them as being completely interchangeable. Selling bicycles is done in the same way as before only now you can create shops that sell either Acme or General Products bikes var alecsCruisers new AcmeBicycleShop var yourNewBike The Lowrider var bobsCruisers new GeneralProductsBicycleShop var yourSecondNewBike The Lowrider Since both manufacturers make bikes in the same styles customers can go into a shop and order a certain style without caring who originally made it. Or if they only want an Acme bike they can go to the shops that only sell Acme bikes. Adding additional manufacturers is easy simply create another subclass of BicycleShop and override the createBicycle factory method. You can also modify each subclass to allow for additional models specific to a certain manufacturer. This is the most important feature of the factory pattern. You can write all of your general Bicycle code in the parent class BicycleShop and then defer the actual instantiation of specific Bicycle objects to the subclasses. The general code is all in one place and the code that varies is encapsulated in the subclasses. CHAPTER 7 THE FACTORY PATTERN 99 When Should the Factory Pattern Be Used The simplest way to .

TỪ KHÓA LIÊN QUAN