工厂模式的几种形态:
1.简单工厂模式
2.工厂方法模式
3.抽象工厂模式
1.简单工厂模式
public interface Product {
}
public class A implements Product {
public A(){
System.out.println("制造了A");
}
}
public class B implements Product {
public B(){
System.out.println("制造了B");
}
}
......
public class ProductFactory {
public static Product produce(String productName) throws Exception {
switch (productName) {
case "a":
return new A();
case "b":
return new B();
default:
throw new Exception("没有该产品");
}
}
}
就是根据参数返回不同的实例对象
2.工厂方法模式
public interface Factory {
public Product produce();
}
public interface Product{}
public class A implements Product {
public A(){
System.out.println("制造了A");
}
}
public class B implements Product {
public B(){
System.out.println("制造了B");
}
}
......
public class AFactory implements Factory {
@Override
public Product produce() {
return new A();
}
}
public class BFactory implements Factory {
@Override
public Product produce() {
return new B();
}
}
......
可以自由的扩展自定义的产品和产品工厂
3.抽象工厂模式
public interface Factory {
public ProductA produceA();
public ProductB produceB();
}
public interface ProductA{}
public interface ProductB{}
public class A implements ProductA {
public A(){
System.out.println("制造了A");
}
}
public class B implements ProductA {
public B(){
System.out.println("制造了B");
}
}
......
public class C implements ProductB {
public C(){
System.out.println("制造了C");
}
}
public class D implements ProductB {
public D(){
System.out.println("制造了D");
}
}
......
public class AFactory implements Factory {
@Override
public ProductA produceA() {
return new A();
}
@Override
public ProductB produceB() {
return new C();
}
}
public class BFactory implements Factory {
@Override
public ProductA produceA() {
return new B();
}
@Override
public ProductB produceB() {
return new D();
}
}
......
网友评论