工厂模式分为:简单工厂模式,工厂方法模式,抽象工厂模式
简单工厂模式:
简单工厂模式分离产品的创建者和消费者,有利于软件系统结构的优化;但是由于一切逻辑都集中在一个工厂类中,导致了没有很高的内聚性,同时也违背了“开放封闭原则”。另外,简单工厂模式的方法一般都是静态的,而静态工厂方法是无法让子类继承的,因此,简单工厂模式无法形成基于基类的继承树结构。
示例代码:
public class FoodFactory {
public static Food getFood(String type){
try {
if("MC".equals(type.toUpperCase())){
return McChicken.class.newInstance();
}else if("CHIP".equals(type.toUpperCase())){
return Chips.class.newInstance();
}else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Food getFood(Class<? extends Food> foodClass){
try {
if(McChicken.class.equals(foodClass)){
return McChicken.class.newInstance();
}else if(Chips.class.equals(foodClass)){
return Chips.class.newInstance();
}else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
工厂方法模式:
简单工厂模式严重违背了“开闭原则”,难以拓展,由此产生了工厂方法模式。工厂方法(Factory Method)模式的意义是定义一个创建产品对象的工厂接口,将实际创建工作推迟到子类当中。核心工厂类不再负责产品的创建,这样核心类成为一个抽象工厂角色,仅负责具体工厂子类必须实现的接口,这样进一步抽象化的好处是使得工厂方法模式可以使系统在不修改具体工厂角色的情况下引进新的产品。
示例代码:
定义接口:
public interface FactoryBMW {
BMW createBMW();
}
实现接口:
public class FactoryBMW320 implements FactoryBMW {
@Override
public BMW createBMW() {
return new BMW320();
}
}
public class FactoryBMW523 implements FactoryBMW {
@Override
public BMW createBMW() {
return new BMW523();
}
}
定义实例:
public class BMW {
public BMW(){
}
}
public class BMW320 extends BMW {
public BMW320(){
System.out.println("320");
}
}
public class BMW523 extends BMW {
public BMW523(){
System.out.println("523");
}
}
测试方法:
public class Test {
public static void main(String[] args) {
FactoryBMW factoryBMW = new FactoryBMW320();
factoryBMW.createBMW();
}
}
抽象工厂模式:
定义工厂:
public interface AbstractFactory {
Engine createEngine();
Aircondition createAircondition();
}
public class FactoryBMW320 implements AbstractFactory {
@Override
public Engine createEngine() {
return new EngineA();
}
@Override
public Aircondition createAircondition() {
return new AirconditionA();
}
}
public class FactoryBMW523 implements AbstractFactory {
@Override
public Engine createEngine() {
return new EngineB();
}
@Override
public Aircondition createAircondition() {
return new AirconditionB();
}
}
定义组件:
public interface Aircondition {
}
public class AirconditionA implements Aircondition {
public AirconditionA(){
System.out.println(AirconditionA.class.getSimpleName());
}
}
public class AirconditionB implements Aircondition {
public AirconditionB(){
System.out.println(AirconditionB.class.getSimpleName());
}
}
public interface Engine {
}
public class EngineA implements Engine {
public EngineA(){
System.out.println(EngineA.class.getSimpleName());
}
}
public class EngineB implements Engine {
public EngineB(){
System.out.println(EngineB.class.getSimpleName());
}
}
测试方法:
public class Test {
public static void main(String[] args) {
AbstractFactory factory = new FactoryBMW320();
factory.createEngine();
factory.createAircondition();
}
}
来源:oschina
链接:https://my.oschina.net/u/2319418/blog/1606571