模式定义:
定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使得一个类的实例化延迟到子类。
简单工厂的模式样例应该是如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package com.wzl.design.factory;
public class SimpleFactory { public static Product createdProduct(String type) { if (type.equals("0")) { return new ProductA(); } else if (type.equals("1")) { return new ProductA1(); } else { return null; } } }
interface Product { public void method1(); }
class ProductA implements Product { @Override public void method1() { System.out.println("ProductA.method1 executed."); } }
class ProductA1 implements Product {
@Override public void method1() { System.out.println("ProdcutA1.method1 executed"); } }
abstract class Application { abstract Product createProduct();
Product getObject() { Product product = createProduct(); return product; } }
|