抽象工厂模式

抽象工厂模式实践

定义宝马接口:

package com.whereta.abstractfactory;

/**
 * Vincent 创建于 2016/4/15.
 * 宝马接口:定义宝马车的类型
 */
public interface IBMW {
    void setType();
}

定义宝马车型具体实现类:

package com.whereta.abstractfactory;

/**
 * Vincent 创建于 2016/4/15.
 */
public class BMWX5 implements IBMW {
    public void setType() {
        System.out.println("我是宝马X5");
    }
}
package com.whereta.abstractfactory;

/**
 * Vincent 创建于 2016/4/15.
 */
public class BMWX6 implements IBMW {
    public void setType() {
        System.out.println("我是宝马X6");
    }
}

定义工厂接口:

package com.whereta.abstractfactory;

/**
 * Vincent 创建于 2016/4/15.
 * 宝马工厂接口:定义生成某个型号的宝马的工厂
 */
public interface IBMWFactory {
    IBMW produce();
}

定义工厂实现类:

package com.whereta.abstractfactory;

/**
 * Vincent 创建于 2016/4/15.
 */
public class BMWX5Factory implements IBMWFactory {
    public IBMW produce() {
        System.out.println("我生产BMWX5");
        return new BMWX5();
    }
}
package com.whereta.abstractfactory;

/**
 * Vincent 创建于 2016/4/15.
 */
public class BMWX6Factory implements IBMWFactory {
    public IBMW produce() {
        System.out.println("我生产BMWX6");
        return new BMWX6();
    }
}

测试

package com.whereta.abstractfactory;

/**
 * Vincent 创建于 2016/4/15.
 * 抽象工厂模式:相对于普通工厂模式,如果宝马新出一种车型,只需要新建一个宝马工厂即可,不会影响其他工厂接口和车型接口,有利于扩展
 */
public class Main {
    public static void main(String[] args) {
        IBMWFactory bmwx5Factory=new BMWX5Factory();
        IBMW ibmw = bmwx5Factory.produce();
        ibmw.setType();
    }
}

输出结果:

Connected to the target VM, address: '127.0.0.1:52651', transport: 'socket'
我生产BMWX5
我是宝马X5
Disconnected from the target VM, address: '127.0.0.1:52651', transport: 'socket'

Process finished with exit code 0


个人博客:http://www.whereta.com

转载于:https://my.oschina.net/vincentzhao/blog/660012

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值