1. 程式人生 > 其它 >設計模式之工廠模式(Factory Design Pattern)

設計模式之工廠模式(Factory Design Pattern)

技術標籤:面向物件的設計思想與設計模式

工廠模式就是為了建立一類物件而設計的模式,工廠模式分為三種更加細分的型別:簡單工廠、工廠方法和抽象工廠。

一個普通人,白手起家,在服裝廠工作幾年後,想自己當老闆,但是又沒有太多的資金。只能租個小廠房(作坊)幫別人加工產品。所有的產品不管是生產衣服、帽子、襪子還是內褲都這個小廠房裡生產。

簡單工廠模式,可以理解為一個作坊模式。簡單工廠模式平時是用的最多最常見的。

//服裝
interface Clothing {
    //...
}
//夾克
class Jacket implements Clothing {
    //...
}
//襪子
class Socks implements Clothing {
    //...
}
//帽子
class Cap implements Clothing {
    //...
}

class ClothingFactory {
  
  public Clothing createClothing(String type){
    if ("jacket".equalsIgnoreCase(type)) {
      return new Jacket();
    } else if ("socks".equalsIgnoreCase(type)) {
      return new Socks();
    } else if ("cap".equalsIgnoreCase(type)) {
      return new Cap();
    } 
    return null;
  }  

}

這個普通人賺了些錢之後,擴大了生產。他規劃著多租幾個廠房作車間,把衣服、帽子、襪子、內褲各分到一個車間去生產。這個時候他的公司已經從一個作坊發展成了一個服裝廠。

工廠方法模式,可以理解為一個工廠模式。

//服裝
interface Clothing {
    //...
}
//夾克
class Jacket implements Clothing {
    //...
}
//襪子
class Socks implements Clothing {
    //...
}
//帽子
class Cap implements Clothing {
    //...
}

//服裝廠
interface ClothingFactory {
  
  public Clothing create()

}
//夾克生產車間
public class JacketFactory implements ClothingFactory {
  public Clothing create() {
    return new Jacket();
  }
}
//襪子生產車間
public class SocksFactory implements ClothingFactory {
  public Clothing create() {
    return new Socks();
  }
}
//帽子生產車間
public class CapFactory implements ClothingFactory {
  public Clothing create() {
    return new Cap();
  }
}

這個普通人賺了更多的錢之後,他已經不滿足幫別人貼牌生產,希望有自己的品牌。於是他又擴大了生產。建立了多個分廠,生產自己的品牌產品。不同品牌的產品在不同的車間生產。衣服廠、帽子廠、襪子廠一個個建起來了。

抽象工廠,可以理解為一個集團工廠模式。每個產品都在不同的工廠裡生產,衣服、帽子、襪子還是內褲都在不同工廠裡生產。

//服裝
interface Clothing {
    //...
}

class abstract AbstractClothing implements Clothing {
  private String brand;
  public AbstractClothing(String brand) {
    this.brand = brand;
  }
  //...
}
//夾克
class Jacket extends AbstractClothing implements Clothing {
  public Jacket(String brand) {
     super(brand);
  }
    //...
}
//襪子
class Socks implements Clothing {
  public Socks(String brand) {
     super(brand);
  }
    //...
}
//帽子
class Cap implements Clothing {
  public Cap(String brand) {
     super(brand);
  }
    //...
}

//服裝廠
interface ClothingFactory {
  public Clothing createA();
  public Clothing createB();
}
//夾克生產廠
public class JacketFactory implements ClothingFactory {
  public Clothing createA() {
    return new Jacket('a');
  }
  public Clothing createB() {
    return new Jacket('b');
  }
}
//襪子生產廠
public class SocksFactory implements ClothingFactory {
  public Clothing createA() {
    return new Socks('a');
  }
  public Clothing createB() {
    return new Socks('b');
  }
}
//帽子生產廠
public class CapFactory implements ClothingFactory {
  public Clothing createA() {
    return new Cap('a');
  }
  public Clothing createB() {
    return new Cap('b');
  }
}