public class Factory public static Sample creator if(which==1) return new My Sample else if (which==2) return new His sample Sample s s=Factory. creator(
public class Factory{ public static Sample creator(){ .... if (which==1) return new MySample(); else if (which==2) return new HisSample(); } } Sample s; s=Factory.creator(); s.xxx();
Services Factory note that the factory methods return objects ty ped to an accounting Adapter: lAccountingAdapter f interface rather than a class, so inventory Adapter: INventory Adapter i that the factory can return any tax CalculatorAdapter: ITax CalculatorAdapter implementation of the interface getAccountingAdapter(: lAccountingAdaptelo getInventory Adapter(: INventory Adapter get T ax CalculatorAdapter(: ITax CalculatorAdapter if tax Calculator Adapter ==null // a reflective or data-driven approach to finding the right class: read it from an ∥ external property String className= System get Property( taxcalculator class name"); tax Calculator Adapter =(IT axCalculatorAdapter) Class forName( class Name ). newInstance( return tax CalculatorAdapter;
Factory objects have several advantages ● the responsibility of complex creation分离 到高内聚的 helper objects中 将潜在的复杂的创建对象的逻辑隐癜 ●可进而引入增强性能的内存管理策略,如 object caching or recycling
Factory objects have several advantages: ⚫ the responsibility of complex creation分离 到高内聚的helper objects中 ⚫ 将潜在的复杂的创建对象的逻辑隐藏 ⚫ 可进而引入增强性能的内存管理策略,如 object caching or recycling
e Also is an example of a partial data driven design 通过改变属性值来选择创建不同的 adapter 对象 ● Protected variations: Adapter的实现类 在变化
Also is an example of a partial datadriven design ⚫ 通过改变属性值来选择创建不同的adapter 对象 Protected Variations :Adapter的实现类 在变化
OUTLINE ● Adapter Factory Singleton e Strategy e Composition ● Facade o Observer
OUTLINE Adapter Factory Singleton Strategy Composition Facade Observer