总述
其实这篇博客说的是静态工厂模式,它是简单工厂模式的一种。
类图
工厂模式.png实现
调用
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
try {
Product one = Factory.productProducer(ProductA.class.toString());
one.printProductInformation();
Product two = Factory.productProducer(ProductB.class.toString());
two.printProductInformation();
Product three = Factory.productProducer(Product.class.toString());
three.printProductInformation();
} catch (NullPointerException e) {
System.out.println(e.toString());
}
}
}
输出
这是A产品
这是B产品
java.lang.NullPointerException: 无法生产此种产品
Process finished with exit code 0
工厂
package com.company;
public class Factory {
public static Product productProducer(String type) {
if (type.equals(ProductA.class.toString())) {
return new ProductA();
} else if (type.equals(ProductB.class.toString())) {
return new ProductB();
} else {
throw new NullPointerException("无法生产此种产品");
}
}
}
产品接口
package com.company;
public interface Product {
void printProductInformation();
}
A产品
package com.company;
public class ProductA implements Product {
@Override
public void printProductInformation() {
System.out.println("这是A产品");
}
}
B产品
package com.company;
public class ProductB implements Product {
@Override
public void printProductInformation() {
System.out.println("这是B产品");
}
}
网友评论