工厂模式factory(创建型)

工厂

工厂用来封装对象的创建。


简单工厂模式

一、模式概念

       从设计模式的类型上来说,简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。


二、uml图




工厂方法模式

一、模式概念

是定义一个创建产品对象的工厂接口,让子类决定实例化哪一个类,将实际创建工作推迟到子类当中。


二、uml图




抽象工厂模式

一、模式概念

提供一个接口,用于创建相关或依赖对象的家族,而不用明确指定具体的类型


二、uml图



抽象工厂具有一般性

show code


产品家族

/**
 * Created by supertool on 15-4-21.
 */
public interface IProductorA {
}


/**
 * Created by supertool on 15-4-21.
 */
public class ProductorA1 implements IProductorA{

    public ProductorA1(){
        System.out.println("create A1");
    }

    public void doOther(){
        System.out.println("A1 other");
    }
}


/**
 * Created by supertool on 15-4-21.
 */
public class ProductorA2 implements IProductorA {
    public ProductorA2(){
        System.out.println("create A2");
    }

    public void doOther(){
        System.out.println("A2 other");
    }
}



/**
 * Created by supertool on 15-4-21.
 */
public interface IProductorB {
}


/**
 * Created by supertool on 15-4-21.
 */
public class ProductorB1 implements IProductorB {

    public ProductorB1(){
        System.out.println("create B1");
    }

    public void doOther(){
        System.out.println("B1 other");
    }
}




/**
 * Created by supertool on 15-4-21.
 */
public class ProductorB2 implements IProductorB{
    public ProductorB2(){
        System.out.println("create B2");
    }

    public void doOther(){
        System.out.println("B2 other");
    }
}





抽象工厂

/**
 * Created by supertool on 15-4-21.
 */
public interface AbstractFactory {
    public IProductorA createA();
    public IProductorB createB();
}


public class ConcreteFactory1 implements AbstractFactory {
    @Override
    public IProductorA createA() {
        return new ProductorA1();
    }

    @Override
    public IProductorB createB() {
        return new ProductorB1();
    }
}


/**
 * Created by supertool on 15-4-21.
 */
public class ConcreteFactory2 implements AbstractFactory {
    @Override
    public IProductorA createA() {
        return new ProductorA2();
    }

    @Override
    public IProductorB createB() {
        return new ProductorB2();
    }
}


public class FactoryTest {
    public static void main(String[] args) {
        AbstractFactory factory1 = new ConcreteFactory1();
        System.out.println(factory1.createA());
        System.out.println(factory1.createB());
    }
}


create A1
com.miaozhen.study.mr.model.factory.abstractfactory.ProductorA1@12edcd21
create B1
com.miaozhen.study.mr.model.factory.abstractfactory.ProductorB1@34c45dca



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值