简单工厂
public class FactoryMode {
interface Product {
void hello();
}
static class Product1 implements Product {
@Override
public void hello() {
System.out.println("hello,Product1");
}
}
static class Product2 implements Product {
@Override
public void hello() {
System.out.println("hello,Product2");
}
}
static class SimpleFactory {
public static Product getProduct(String type) {
if ("1".equals(type)) {
return new Product1();
}
if ("2".equals(type)) {
return new Product2();
} else {
return null;
}
}
}
public static void main(String[] args) {
Product product = SimpleFactory.getProduct("1");
product.hello();
}
}
工厂方法
public class FactoryMode {
interface Factory {
Product create();
}
interface Product {
void hello();
}
static class Factory1 implements Factory {
@Override
public Product create() {
return new Product1();
}
}
static class Factory2 implements Factory {
@Override
public Product create() {
return new Product2();
}
}
static class Product1 implements Product {
@Override
public void hello() {
System.out.println("hello,Product1");
}
}
static class Product2 implements Product {
@Override
public void hello() {
System.out.println("hello,Product2");
}
}
public static void main(String[] args) {
Factory factory = new Factory1();
Product product = factory.create();
product.hello();
}
}
工厂方法跟简单工厂的组合
static class FactoryMap {
private static final Map<String,Factory> map = new HashMap<>();
static {
map.put("1",new Factory1());
map.put("2",new Factory2());
}
public static Factory getFactory(String type) {
if (StringUtils.isEmpty(type)) {
return null;
}
return map.get(type);
}
}
public static void main(String[] args) {
Factory factory = FactoryMap.getFactory("1");
Product product = factory.create();
product.hello();
}
总结
- 简单工厂把对象的创建过程抽离出来
- 把独立的代码块抽离出来让代码逻辑更清晰,可读性更好
- 利用多态去实现工厂方法模式,可以去掉if判断,新加类型时的改动,更加符合开闭原则
网友评论