工厂模式核心作用

  • 实例化对象,用工厂方法代替 new 操作
  • 将选择实现类、创建对象统一管理和控制,从而将调用者和我们的实现类解耦


工厂模式

  • 简单工厂模式
    • 用来生产同一等级结构中的任意产品。对于增加新的产品,需要修改已有代码
  • 工厂方法模式
    • 用来生产同一等级结构中的固定产品。支持增加任意产品
  • 抽象工厂模式
    • 用来生产不同产品族的全部产品。对于增加新的产品,无能为力,支持增加产品族


简单工厂模式



接口代码(CarInterface.java)

package shejimoshi.factory.simplefactory;

public interface CarInterface {
void run();
}


实现类代码

package shejimoshi.factory.simplefactory;

public class Benchi implements CarInterface {

@Override
public void run() {
System.out.println("我是奔驰");
}

}
package shejimoshi.factory.simplefactory;

public class Baoma implements CarInterface {

@Override
public void run() {
System.out.println("我是宝马");
}

}

工厂类代码(CarFactory.java
package shejimoshi.factory.simplefactory;

public class CarFactory {

public static CarInterface createCar(String type) {
CarInterface car = null;

if ("奔驰".equals(type)) {
return new Benchi();
} else if ("宝马".equals(type)) {
return new Baoma();
}

return car;
}

}

调用代码(Client.java
package shejimoshi.factory.simplefactory;

public class Client {

public static void main(String[] args) {
CarInterface c1 = CarFactory.createCar("奔驰");
CarInterface c2 = CarFactory.createCar("宝马");

c1.run();
c2.run();
}

}





工厂方法模式



接口类代码

CarInterface.java

package shejimoshi.factory.factorymethod;

public interface CarInterface {
void run();
}

CarFactory.java

package shejimoshi.factory.factorymethod;

public class BaomaFactory implements CarFactory {

@Override
public CarInterface createCar() {
return new Baoma();
}

}


实现类代码

Benchi.java

package shejimoshi.factory.factorymethod;

public class Benchi implements CarInterface {

@Override
public void run() {
System.out.println("我是奔驰");
}

}

BenchiFactory.java

package shejimoshi.factory.factorymethod;

public class BenchiFactory implements CarFactory {

@Override
public CarInterface createCar() {
return new Benchi();
}

}

Baoma.java

package shejimoshi.factory.factorymethod;

public class Baoma implements CarInterface {

@Override
public void run() {
System.out.println("我是宝马");
}

}

BaomaFactory.java

package shejimoshi.factory.factorymethod;

public class BaomaFactory implements CarFactory {

@Override
public CarInterface createCar() {
return new Baoma();
}

}


调用代码(Client.java)

package shejimoshi.factory.factorymethod;

public class Client {
public static void main(String[] args) {
CarInterface c1 = new BenchiFactory().createCar();
CarInterface c2 = new BaomaFactory().createCar();

c1.run();
c2.run();
}
}





回到顶部