pattern:Abstract Factory (创建型模式)模式笔记

 

Abstract Factory (创建型模式)

此模式是对Factory的扩展,就是说原来的工厂是负责对某一类对象进行创建,现在是负责对某一组对象进行创建:老师负责一个个学生,校长负责一个个班(班又是由一个个学生组成)

 Problem of new function:

 实现依赖,不能应对具体实例化类型的变化

解决思路:

 封装变化点:哪里变化,那里封装

 封装“对象创建”

简单(静态)工厂

Class RoadFactory{

 Public static Road CreateRoad()

 {

     Return new Road();

}

}

//Create a Road object

Road road = roadFactory.CreateRoad();//此处相对稳定

New Problem:When there are a serial of request, Class RoadFactory may be the point of variety, so we need a new model, abstract factory

Motivation: “一系列相互依赖的对象”的创建;同时,由于需求的变化,往往存在“更多系列对象”的创建工作。

封装:在需求不稳定时,避免客户程序和“多系列具体对象创建工作”的紧耦合。

Intent:提供一个接口,让接口负责创建一系列“相关或者相互依赖的对象”,无须制定具体的类。


实例:

public abstract class Road

{

}

 public abstract class Building

{

}

public abstract class FacilitiesFactory

{

 publice abstract Road CreateRoad();

 publice abstract Building Create Building ();

}

//客户程序

class GameManager{

 FacilitiesFactory facilitiesFactory

   Raod road;

   Building building;

 public GameManager(FacilitiesFactory facilitiesFactory);

 {

    This.facilitiesFactory = facilitiesFactory;

}

publice void BuildGameFacilities()

{

  road = facilitiesFactory.CreateRoad();

   building = facilitiesFactory.CreateBuilding();

}

public void Run(){

 //Call the function of any class list above such as road.aa();

}

}

class App

{

 publice static void main()

{

     GameManager g = new GameManager(?????);

     g.BuildGameFacilites();

     g.Run();

}

}

So we have the basic abustruct, then the focus is on the line bolded GameManager g = new GameManager(?????);, suppose first we need a class style scene then we may be asked to change it to modern style, how can we do it.first we define the series class to realize class style, second define another series class for modern style, finally we can only change the “??????”

public class ModernRoad            public class ClassRoad

{                                {

}                                }

public class ModernBuilding         public class ClassBuilding

{                               {

}                                }

public class ModernFacilitiesFactory           public class ClassFacilitiesFactory

{                                        {

 publice abstract Road CreateRoad();            publice abstract Road CreateRoad()

 publice abstract Building CreateBuilding ();      publice abstract Building CreateBuilding ()

}                                        }

GameManager g = new GameManager(new ClassFacilitiesFactory());

GameManager g = new GameManager(new ModernFacilitiesFactory());

原文地址:https://www.cnblogs.com/xiachong/p/1070770.html