所有工厂以造枪功能模拟
普通工厂方法
简易理解:一个造枪厂能造枪,给什么材料,就用对应的机器造什么枪,枪都能发射子弹;
工厂造的所有枪都能打子弹
public interface Gun {
public void shot();
}
枪厂里有造AK和M4的机器来造对应的枪
public class AK implements Gun{
@Override
public void shot() {
System.out.println("this is a AK bullet!");
}
}
public class M4 implements Gun{
@Override
public void shot() {
System.out.println("this is a m4 bullet!");
}
}
这是造枪工厂,给什么材料造什么枪
public class GunFactory {
public Gun produce(String type) {
if ("ak".equals(type)) {
return new AK();
} else if ("m4".equals(type)) {
return new M4();
} else {
System.out.println("本工厂不能造该类型的枪!");
return null;
}
}
}
测试:
public class ShotTest {
public static void main(String[] args) {
GunFactory factory = new GunFactory();
AK ak= factory.produce("ak");
ak.shot();
}
}
结果:
this is a AK bullet!
多个工厂方法
对普通工厂模式改进,枪厂发展扩大,原先的两台机器发展成了两个部门,避免造枪时材料给错了枪造不出来的问题,现在直接去找造枪部门,让不同部门造不同枪;
public class GunFactory {
public Gun produceAK() {
return new AK();
}
public Gun produceM4() {
return new M4();
}
}
测试:
public class ShotTest {
public static void main(String[] args) {
GunFactory factory = new GunFactory();
AK ak= factory.produceAK();
ak.shot();
}
}
结果:
this is a AK bullet!
静态工厂方法
造枪厂继续发展壮大,不需要再去工厂提货了
public class GunFactory {
public static Gun produceAK() {
return new AK();
}
public static Gun produceM4() {
return new M4();
}
}
测试:
public class ShotTest {
public static void main(String[] args) {
AK ak= GunFactory.produceAK();
ak.shot();
}
}
结果:
this is a AK bullet!
抽象工厂
造枪厂凭借两种产品飞速发展,规模迅速扩大,原先两个龙头部门直接发展成为两个子厂,总厂发展成行业大头,造枪名声在外,后续随时准备开设其他子厂;
总厂负责管理子厂业务,拟定发展方向
public interface GunFactory{
public Gun produce();
}
造AK子厂
public class AkFactory implements GunFactory{
@Override
public Gun produce(){
return new AK();
}
}
造M4子厂
public class M4Factory implements GunFactory{
@Override
public Gun produce(){
return new M4();
}
}
测试:
public class Test {
public static void main(String[] args) {
GunFactory gunFactory = new AkFactory();
Gun gun = gunFactory.produce();
gun.shot();
}
}
抽象工厂的拓展性极好!