设计模式——工厂方法模式

155 阅读1分钟

最新修改已更新到github

工厂方法模式即父类定义接口,具体的实现交给子类来做,从而提供开闭原则

/**
 * @author maikec
 * @date 2019/5/10
 */
public abstract class AbstractFactory {
    /**
     * 创建产品
     * @param owner
     * @return AbstractProduct
     */
    protected abstract AbstractProduct createProduct(String owner);

    /**
     * 把产品注入数组
     * @param product
     */
    protected abstract void registerProduct(AbstractProduct product);

    /**
     * 创建产品并注入列表
     * @return
     */
    public final AbstractProduct create(String owner){
        AbstractProduct product = createProduct(owner);
        registerProduct(product);
        return product;
    }
}

/**
 * @author maikec
 * @date 2019/5/10
 */
public abstract class AbstractProduct {
    /**
     * 使用
     */
    public abstract void use();
}

/**
 * @author maikec
 * @date 2019/5/10
 */
public class IDCardFactory extends AbstractFactory {
    private final List<IDCard> idCards = new LinkedList<>(  );
    @Override
    protected AbstractProduct createProduct(String owner) {
        if (null == owner){
            throw new IllegalArgumentException( "owner cannot be null" );
        }
        return new IDCard( owner );
    }

    @Override
    protected void registerProduct(AbstractProduct product) {
        if (!(product instanceof IDCard)){
            throw new IllegalArgumentException( "product should be IDCard instance" );
        }
        idCards.add( (IDCard) product );
    }
}

/**
 * @author maikec
 * @date 2019/5/10
 */
public class IDCard extends AbstractProduct {
    public IDCard(String owner){
        this.owner = owner;
    }
    private String owner;

    public String getOwner() {
        return owner;
    }

    @Override
    public void use() {
        System.out.println( "This is " + owner + " IDCard" );
    }
}

/**
 * @author maikec
 * @date 2019/5/10
 */
public class FactoryMethodDemo {
    public static void main(String[] args) {
        AbstractFactory factory = new IDCardFactory();
        AbstractProduct product = factory.create( "Maikec" );
        product.use();
    }
}

附录

github.com/maikec/patt… 个人GitHub设计模式案例

声明

引用该文档请注明出处