设计模式之简单工厂(factory)模式
1.不使用设计模式
package com.lucky.pattern.factory;
/**
* @author: LIJY
* @Description: 不使用设计模式
* @Date: 2021/10/2 22:47
*/
public class WithoutFactoryPatternDemo {
public static void main(String[] args) {
// Product product = new Product("测试");
// System.out.println(product);
Product2 product2 = new Product2("测试2");
System.out.println(product2);
}
// public static class Product {
// private String name;
//
// public Product(String name) {
// this.name = name;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return "Product{" +
// "name='" + name + '\'' +
// '}';
// }
// }
public static class Product2 {
private String name;
public Product2(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
'}';
}
}
}
缺点:
上述实例中,是面向一个类来编程的,new 来创建类的实例,调用其方法和参数。
如果Product的类名进行了变更,其内部的构造也会变更,那么调用该实例的地方都要做变更修改,有100个调用就要修改100个地方,修改所有的new Product()的地方,代码可维护性和可扩展性极差。
2. 使用设计模式
package com.lucky.pattern.factory;
/**
* @author: LIJY
* @Description: 使用设计模式
* @Date: 2021/10/2 22:56
*/
public class FactoryPatternDemo {
public static void main(String[] args) {
Product product = ProductFactory.create();
product.execute();
}
public interface Product{
void execute();
}
public static class ProductImpl1 implements Product {
public void execute() {
System.out.println("产品1的功能实现");
}
}
public static class ProductImpl2 implements Product {
public void execute() {
System.out.println("产品2的功能实现");
}
}
public static class ProductFactory {
public static Product create() {
// return new ProductImpl1();
return new ProductImpl2();
}
}
}
优点:
Product的实现变了,只需要修改一个地方,ProductFactory 中 new 的对象。其他调用的地方不需要修改。
工厂模式在spring中最常见。
网友评论