抽象工廠模式概念
抽象工廠模式屬於創建型模式,它提供一個創建一系列相關或者相互依賴對象的接口,而無需指定它們具體的類。
抽象工廠模式與工廠模式的區別
- 工廠模式是針對一種產品
- 抽象工廠模式是針對多種產品(至少兩種)
抽象工廠模式類圖
抽象工廠模式實現
描述:抽象工廠模式一個工廠可以製作男款和女款的衣服,而工廠模式一個工廠只能製作一種款式的衣服
public abstract class AbstractClothesFactory {
abstract AbstractFemaleClothes createFClothes();
abstract AbstractMaleClothes createMClothes();
}
class ChildrenFactory extends AbstractClothesFactory{
@Override
AbstractFemaleClothes createFClothes() {
return new FChildrenClothes();
}
@Override
AbstractMaleClothes createMClothes() {
return new MChildrenClothes();
}
}
class MiddleAgeFactory extends AbstractClothesFactory{
@Override
AbstractFemaleClothes createFClothes() {
return new FMiddleAgeClothes();
}
@Override
AbstractMaleClothes createMClothes() {
return new MMiddleAgeClothes();
}
}
public abstract class AbstractFemaleClothes {
abstract void applayFor();
}
class FChildrenClothes extends AbstractFemaleClothes{
@Override
void applayFor() {
System.out.println("女孩穿的衣服");
}
}
class FMiddleAgeClothes extends AbstractFemaleClothes{
@Override
void applayFor() {
System.out.println("中年女性穿的衣服");
}
}
public abstract class AbstractMaleClothes {
abstract void applayFor();
}
class MChildrenClothes extends AbstractMaleClothes{
@Override
void applayFor() {
System.out.println("男孩穿的衣服");
}
}
class MMiddleAgeClothes extends AbstractMaleClothes{
@Override
void applayFor() {
System.out.println("中年男士穿的衣服");
}
}
public class Main {
public static void main(String[] args) {
AbstractClothesFactory childrenFactory = new ChildrenFactory();
AbstractClothesFactory middleAgeFactory = new MiddleAgeFactory();
AbstractFemaleClothes fChildrenClothes = childrenFactory.createFClothes();
fChildrenClothes.applayFor();
AbstractMaleClothes mChildrenClothes = childrenFactory.createMClothes();
mChildrenClothes.applayFor();
AbstractFemaleClothes fMiddleAgeClothes = middleAgeFactory.createFClothes();
fMiddleAgeClothes.applayFor();
AbstractMaleClothes mMiddleAgeClothes = middleAgeFactory.createMClothes();
mMiddleAgeClothes.applayFor();
}
}
輸出結果如下
抽象工廠模式的優缺點
優點
- 便於交換產品系列,也就是說從兒童系列與中年系列之間的切換很容易,只需改變工廠即可
- 客戶端與實例創建過程進行了分離,一切都交給工廠來處理並且產品系列具體類名也是不得知得(返回的是抽象接口)
缺點
當要在增加一種款式時,那麼要修改之處很多(AbstractClothesFactory和它的具體實現類都要進行修改)
-_-沒有天才,只有勤奮的天才!