定义宝马接口:
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