SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Department of Computer Science & Engineering in Hanyang University                                 SINCE 2006




                                           Abstract Factor y

                                                                                 HPC and OT Lab.
                                                                                    23.Jan.2007.
                                                                     M.S. 1st   Choi, Hyeon Seok




                                                                                                           1
Contents

       Creational Patterns

       Introduction
       Structure, Participants and Collaborations
       Consequences
       Implementation
       Sample code
       Related Patterns
       References



High Performance Computing & Object Technology Laboratory in CSE   2
Creational Patterns

       Themes
              All encapsulate knowledge about which concrete classes
               the system uses
              Hide how instances of these classes are created and put
               together

       Creational patterns scope
              Class : Use inheritance to vary the class that’s
               instantiated
              Object : Delegate instantiation to another object




High Performance Computing & Object Technology Laboratory in CSE         3
Intent of Abstract Factory

       Provide an interface for creating families of related
        or dependent objects without specifying their
        concrete classes.

                       WidgetFactory
                     +CreateScrollBar()                                                                Clien
                     +CreateWindow()

                                                                                 Window



                                                                   PMWindow           MotifWindonw
      MotifWidgetFactory             PMWidgetFactory
     +CreateScrollBar()             +CreateScrollBar()
     +CreateWindow()                +CreateWindow()

                                                                             ScrollBar



                                                                   PMScrollBar        MotifScrollBar




High Performance Computing & Object Technology Laboratory in CSE                                               4
Applicability

       Independent of how its objects are created,
        composed, and represented

       Configured with one of multiple families of
        products.

       A family of related objects is designed to be used
        together, and you need to enforce this constraint.

       Provide a class library of products, and you want to
        reveal just their interfaces, not implementations.



High Performance Computing & Object Technology Laboratory in CSE   5
Structure, Participants and Collaborations
                                         Declare an interface
                                       (create product object)

                                                                                Declare an interface
                    AbstractFactory
                                                                                 (product object)
                   +CreateProductA()                                                                   Client
                   +CreateProductB()

                                                                             AbstractProductA



                                                                        ProductA2        ProductA1
     ConcreteFactory1              ConcreteFactory
                                                 2
    +CreateProductA()              +CreateProductA()
    +CreateProductB()              +CreateProductB()

                                                                             AbstractProductB

   Implement operation
  (create product object)
                                                                        ProductB2        ProductB1



                                                                   Implement operation
                                                                     (product object)




High Performance Computing & Object Technology Laboratory in CSE                                                6
Consequences

       Advantages
              Isolate concrete classes.

              Make exchanging product families easy.

              Promote consistency among products.


       Disadvantages
              Supporting new kinds of products is difficult.




High Performance Computing & Object Technology Laboratory in CSE   7
Implementation (1/2)

       Factories as singletons
              Application needs only one instance of a
               ConcreteFactory

       Creating the products
              ConcreteProduct define a factory method for each
               object.
              If many product families are possible, the concrete
               factory can be implemented using the prototype pattern.

       Defining extensible factories
              Add a parameter to operation that create objects
               ex) Object make (ObjectType type);




High Performance Computing & Object Technology Laboratory in CSE         8
Implementation (2/2)

       Factory method and Prototype
            AbstractFactor
          +CreateProductA()                                                                           Client
          +CreateProductB()
                                                                                   Prototype
                                                                                    (clone)
                                                                   AbstractProductA
                                                                   +clone()
           ConcreteFactory
                         1
    -ProductA : AbstractProductA
    -ProductB : AbstractProductB                       ProductA2       ProductA1          ProductA3
    +CreateProductA  ()                           +clone()         +clone()           +clone()
    +CreateProductB  ()
                             Factory
                             method                                AbstractProductB
                                                                   +clone()



                                                       ProductB2       ProductB1          ProductB3
                                                  +clone()         +clone()           +clone()




High Performance Computing & Object Technology Laboratory in CSE                                               9
Sample code (1/5)

          ---
          [MazeGame::CreateMaze]--------------------------------------------

          Maze *MazeGame::CreateMaze()
          {
              Maze *aMaze = new Maze();
              Room *r1 = new Room(1);
              Room *r2 = new Room(2);
              Door *theDoor = new Door(r1, r2);

                 aMaze->AddRoom(r1);
                 aMaze->AddRoom(r2);                               // add room

                 r1->SetSide(North, new Wall); // set side
                 r1->SetSide(East, theDoor);
                 r1->SetSide(South, new Wall);
                 r1->SetSide(West, new Wall);

                 r2->SetSide(North, new Wall);
                 r2->SetSide(East, new Wall);
                 r2->SetSide(South, new Wall);
                 r2->SetSide(West, theDoor);

                 return aMaze;
          };
High Performance Computing & Object Technology Laboratory in CSE                 10
Sample code (2/5)

          ---[Class
          MazeFactory]-----------------------------------------------

          class MazeFactory
          {
              public:
                   MazeFactory();
                   // Factory method
                   virtual Maze *MakeMaze() const
                   {
                       return new Maze;
                   }
                   virtual Wall *MakeWall() const
                   {
                       return new Wall;
                   }
                   virtual Room *MakeRoom(int n) const
                   {
                       return new Room(n);
                   }
                   virtual Door *MakeDoor(Room *r1, Room *r2) const
                   {
                       return new Door(r1, r2);
                   }
          };
High Performance Computing & Object Technology Laboratory in CSE        11
Sample code (3/5)
          ---
          [MazeGame::CreateMaze]--------------------------------------------

          // use to MazeFactory
          Maze *MazeGame::CreateMaze(MazeFactory &factory)
          {
              Maze *aMaze = factory.MakeMaze();
              Room *r1 = factory.MakeRoom (1);
              Room *r2 = factory.MakeRoom(2);
              Door *theDoor = factory.MakeDoor(r1, r2);

                 aMaze->AddRoom(r1);
                 aMaze->AddRoom(r2);

                 r1->SetSide(North, factory.MakeWall());
                 r1->SetSide(East, theDoor);
                 r1->SetSide(South, factory.MakeWall());
                 r1->SetSide(West, factory.MakeWall());

                 r2->SetSide(North, factory.MakeWall());
                 r2->SetSide(East, factory.MakeWall());
                 r2->SetSide(South, factory.MakeWall());
                 r2->SetSide(West, theDoor);

                 return aMaze;
           }
High Performance Computing & Object Technology Laboratory in CSE               12
Sample code (4/5)

          ---[class
          EnchantedMazeFactory]--------------------------------------

          class EnchantedMazeFactory: public MazeFactory
          {
              public:
                   EnchantedMazeFactory();

                         // overrided to factory method
                         virtual Room *MakeRoom(int n) const
                         {
                             return new EnchantedRoom(n, CastSpell());
                         }
                         virtual Door *MakeDoor(Room *r1, Room *r2) const
                         {
                             return new DoorNeedingSpell(r1, r2);
                         }

                 protected:
                      Spell *CastSpell() const;
          };




High Performance Computing & Object Technology Laboratory in CSE            13
Sample code (5/5)

          ---[class BombedMazeFactory]--------------------------------------

          class BombedMazeFactory: public MazeFactory
          {
              public:
                   BombedMazeFactory();

                         // overrided to factory method
                         virtual Wall *MakeWall() const
                         {
                             return new BombedWall;
                         }

                         virtual Room *MakeRoom(int n) const
                         {
                             return new RoomWithABomb(n);
                         }

          };

          MazeGame game;
          BombedMazeFactory factory;
          game.CreateMaze(factory);


High Performance Computing & Object Technology Laboratory in CSE               14
Related Patterns

       Abstract Factory classes are often implemented
        with Factory method
       Abstract Factory and Factory can be implemented
        using Prototype
       A Concrete factory is often a Singleton




High Performance Computing & Object Technology Laboratory in CSE   15
References
       [1] Erich Gamma, Richard Helm, Ralph Johnson, John
           Vlissides: Design Patterns Elements of Reusable Object-
           Oriented Software. Addison Wesley, 2000

       [2] 장세찬 : C++ 로 배우는 패턴의 이해와 활용 . 한빛 미디어 ,
         2004

       [3] Eric Freeman, Elisabeth Freeman, 서환수 역 : Head First
           Design Patterns. 한빛 미디어 , 2005




High Performance Computing & Object Technology Laboratory in CSE     16

Weitere ähnliche Inhalte

Andere mochten auch

To become Open Source Contributor
To become Open Source ContributorTo become Open Source Contributor
To become Open Source Contributor
DaeMyung Kang
 
프로그래머로 사는 법 Ch1
프로그래머로 사는 법 Ch1프로그래머로 사는 법 Ch1
프로그래머로 사는 법 Ch1
HyeonSeok Choi
 
프로그래머로사는법 Ch10
프로그래머로사는법 Ch10프로그래머로사는법 Ch10
프로그래머로사는법 Ch10
HyeonSeok Choi
 
Domain driven design ch9
Domain driven design ch9Domain driven design ch9
Domain driven design ch9
HyeonSeok Choi
 
서버인프라를지탱하는기술3_2_3
서버인프라를지탱하는기술3_2_3서버인프라를지탱하는기술3_2_3
서버인프라를지탱하는기술3_2_3
HyeonSeok Choi
 
Code 11 논리 게이트
Code 11 논리 게이트Code 11 논리 게이트
Code 11 논리 게이트
HyeonSeok Choi
 
CODE Ch.21 버스에 올라 탑시다
CODE Ch.21 버스에 올라 탑시다CODE Ch.21 버스에 올라 탑시다
CODE Ch.21 버스에 올라 탑시다
HyeonSeok Choi
 
프로그래머로 사는 법 Ch14
프로그래머로 사는 법 Ch14프로그래머로 사는 법 Ch14
프로그래머로 사는 법 Ch14
HyeonSeok Choi
 
Refactoring 메소드 호출의 단순화
Refactoring 메소드 호출의 단순화Refactoring 메소드 호출의 단순화
Refactoring 메소드 호출의 단순화
HyeonSeok Choi
 

Andere mochten auch (20)

Chean code chapter 1
Chean code chapter 1Chean code chapter 1
Chean code chapter 1
 
HTTP 완벽가이드 1장.
HTTP 완벽가이드 1장.HTTP 완벽가이드 1장.
HTTP 완벽가이드 1장.
 
함수적 사고 2장
함수적 사고 2장함수적 사고 2장
함수적 사고 2장
 
To become Open Source Contributor
To become Open Source ContributorTo become Open Source Contributor
To become Open Source Contributor
 
Ooa&d
Ooa&dOoa&d
Ooa&d
 
Clean code ch15
Clean code ch15Clean code ch15
Clean code ch15
 
프로그래머로 사는 법 Ch1
프로그래머로 사는 법 Ch1프로그래머로 사는 법 Ch1
프로그래머로 사는 법 Ch1
 
프로그래머로사는법 Ch10
프로그래머로사는법 Ch10프로그래머로사는법 Ch10
프로그래머로사는법 Ch10
 
SICP_2.5 일반화된 연산시스템
SICP_2.5 일반화된 연산시스템SICP_2.5 일반화된 연산시스템
SICP_2.5 일반화된 연산시스템
 
C++ api design 품질
C++ api design 품질C++ api design 품질
C++ api design 품질
 
Domain driven design ch9
Domain driven design ch9Domain driven design ch9
Domain driven design ch9
 
서버인프라를지탱하는기술3_2_3
서버인프라를지탱하는기술3_2_3서버인프라를지탱하는기술3_2_3
서버인프라를지탱하는기술3_2_3
 
Code 11 논리 게이트
Code 11 논리 게이트Code 11 논리 게이트
Code 11 논리 게이트
 
Code1_2
Code1_2Code1_2
Code1_2
 
CODE Ch.21 버스에 올라 탑시다
CODE Ch.21 버스에 올라 탑시다CODE Ch.21 버스에 올라 탑시다
CODE Ch.21 버스에 올라 탑시다
 
MiningTheSocialWeb.Ch2.Microformat
MiningTheSocialWeb.Ch2.MicroformatMiningTheSocialWeb.Ch2.Microformat
MiningTheSocialWeb.Ch2.Microformat
 
Domain driven design ch1
Domain driven design ch1Domain driven design ch1
Domain driven design ch1
 
프로그래머로 사는 법 Ch14
프로그래머로 사는 법 Ch14프로그래머로 사는 법 Ch14
프로그래머로 사는 법 Ch14
 
Mining the social web 6
Mining the social web 6Mining the social web 6
Mining the social web 6
 
Refactoring 메소드 호출의 단순화
Refactoring 메소드 호출의 단순화Refactoring 메소드 호출의 단순화
Refactoring 메소드 호출의 단순화
 

Ähnlich wie Abstract factory petterns

27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
Quang Suma
 
Use Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDEUse Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDE
Benjamin Cabé
 
Factory Pattern
Factory PatternFactory Pattern
Factory Pattern
Deepti C
 

Ähnlich wie Abstract factory petterns (20)

Design patterns
Design patternsDesign patterns
Design patterns
 
27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples27418524 design-patterns-dot-net-with-examples
27418524 design-patterns-dot-net-with-examples
 
Use Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDEUse Eclipse technologies to build a modern embedded IDE
Use Eclipse technologies to build a modern embedded IDE
 
Unit 2-Design Patterns.ppt
Unit 2-Design Patterns.pptUnit 2-Design Patterns.ppt
Unit 2-Design Patterns.ppt
 
Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)Factory method pattern (Virtual Constructor)
Factory method pattern (Virtual Constructor)
 
Desing Patterns Summary - by Jim Fawcett
Desing Patterns Summary - by Jim FawcettDesing Patterns Summary - by Jim Fawcett
Desing Patterns Summary - by Jim Fawcett
 
C# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slidesC# Tutorial MSM_Murach chapter-15-slides
C# Tutorial MSM_Murach chapter-15-slides
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Software System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptxSoftware System Architecture-Lecture 6.pptx
Software System Architecture-Lecture 6.pptx
 
Design Pattern For C# Part 1
Design Pattern For C# Part 1Design Pattern For C# Part 1
Design Pattern For C# Part 1
 
How to create an Angular builder
How to create an Angular builderHow to create an Angular builder
How to create an Angular builder
 
Mock with Mockito
Mock with MockitoMock with Mockito
Mock with Mockito
 
Factory Pattern
Factory PatternFactory Pattern
Factory Pattern
 
A coding fool design patterns
A coding fool design patternsA coding fool design patterns
A coding fool design patterns
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
 
Test automation design patterns
Test automation design patternsTest automation design patterns
Test automation design patterns
 
Design Patterns in Cocoa Touch
Design Patterns in Cocoa TouchDesign Patterns in Cocoa Touch
Design Patterns in Cocoa Touch
 
Acceleo Code Generation
Acceleo Code GenerationAcceleo Code Generation
Acceleo Code Generation
 
Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 

Mehr von HyeonSeok Choi

Mehr von HyeonSeok Choi (20)

밑바닥부터시작하는딥러닝 Ch05
밑바닥부터시작하는딥러닝 Ch05밑바닥부터시작하는딥러닝 Ch05
밑바닥부터시작하는딥러닝 Ch05
 
밑바닥부터시작하는딥러닝 Ch2
밑바닥부터시작하는딥러닝 Ch2밑바닥부터시작하는딥러닝 Ch2
밑바닥부터시작하는딥러닝 Ch2
 
프로그래머를위한선형대수학1.2
프로그래머를위한선형대수학1.2프로그래머를위한선형대수학1.2
프로그래머를위한선형대수학1.2
 
알고리즘 중심의 머신러닝 가이드 Ch04
알고리즘 중심의 머신러닝 가이드 Ch04알고리즘 중심의 머신러닝 가이드 Ch04
알고리즘 중심의 머신러닝 가이드 Ch04
 
딥러닝 제대로시작하기 Ch04
딥러닝 제대로시작하기 Ch04딥러닝 제대로시작하기 Ch04
딥러닝 제대로시작하기 Ch04
 
밑바닥부터시작하는딥러닝 Ch05
밑바닥부터시작하는딥러닝 Ch05밑바닥부터시작하는딥러닝 Ch05
밑바닥부터시작하는딥러닝 Ch05
 
7가지 동시성 모델 4장
7가지 동시성 모델 4장7가지 동시성 모델 4장
7가지 동시성 모델 4장
 
Bounded Context
Bounded ContextBounded Context
Bounded Context
 
DDD Repository
DDD RepositoryDDD Repository
DDD Repository
 
DDD Start Ch#3
DDD Start Ch#3DDD Start Ch#3
DDD Start Ch#3
 
실무로 배우는 시스템 성능 최적화 Ch8
실무로 배우는 시스템 성능 최적화 Ch8실무로 배우는 시스템 성능 최적화 Ch8
실무로 배우는 시스템 성능 최적화 Ch8
 
실무로 배우는 시스템 성능 최적화 Ch7
실무로 배우는 시스템 성능 최적화 Ch7실무로 배우는 시스템 성능 최적화 Ch7
실무로 배우는 시스템 성능 최적화 Ch7
 
실무로 배우는 시스템 성능 최적화 Ch6
실무로 배우는 시스템 성능 최적화 Ch6실무로 배우는 시스템 성능 최적화 Ch6
실무로 배우는 시스템 성능 최적화 Ch6
 
Logstash, ElasticSearch, Kibana
Logstash, ElasticSearch, KibanaLogstash, ElasticSearch, Kibana
Logstash, ElasticSearch, Kibana
 
실무로배우는시스템성능최적화 Ch1
실무로배우는시스템성능최적화 Ch1실무로배우는시스템성능최적화 Ch1
실무로배우는시스템성능최적화 Ch1
 
HTTP 완벽가이드 21장
HTTP 완벽가이드 21장HTTP 완벽가이드 21장
HTTP 완벽가이드 21장
 
HTTP 완벽가이드 16장
HTTP 완벽가이드 16장HTTP 완벽가이드 16장
HTTP 완벽가이드 16장
 
HTTPS
HTTPSHTTPS
HTTPS
 
HTTP 완벽가이드 6장.
HTTP 완벽가이드 6장.HTTP 완벽가이드 6장.
HTTP 완벽가이드 6장.
 
Cluster - spark
Cluster - sparkCluster - spark
Cluster - spark
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Abstract factory petterns

  • 1. Department of Computer Science & Engineering in Hanyang University SINCE 2006 Abstract Factor y HPC and OT Lab. 23.Jan.2007. M.S. 1st Choi, Hyeon Seok 1
  • 2. Contents  Creational Patterns  Introduction  Structure, Participants and Collaborations  Consequences  Implementation  Sample code  Related Patterns  References High Performance Computing & Object Technology Laboratory in CSE 2
  • 3. Creational Patterns  Themes  All encapsulate knowledge about which concrete classes the system uses  Hide how instances of these classes are created and put together  Creational patterns scope  Class : Use inheritance to vary the class that’s instantiated  Object : Delegate instantiation to another object High Performance Computing & Object Technology Laboratory in CSE 3
  • 4. Intent of Abstract Factory  Provide an interface for creating families of related or dependent objects without specifying their concrete classes. WidgetFactory +CreateScrollBar() Clien +CreateWindow() Window PMWindow MotifWindonw MotifWidgetFactory PMWidgetFactory +CreateScrollBar() +CreateScrollBar() +CreateWindow() +CreateWindow() ScrollBar PMScrollBar MotifScrollBar High Performance Computing & Object Technology Laboratory in CSE 4
  • 5. Applicability  Independent of how its objects are created, composed, and represented  Configured with one of multiple families of products.  A family of related objects is designed to be used together, and you need to enforce this constraint.  Provide a class library of products, and you want to reveal just their interfaces, not implementations. High Performance Computing & Object Technology Laboratory in CSE 5
  • 6. Structure, Participants and Collaborations Declare an interface (create product object) Declare an interface AbstractFactory (product object) +CreateProductA() Client +CreateProductB() AbstractProductA ProductA2 ProductA1 ConcreteFactory1 ConcreteFactory 2 +CreateProductA() +CreateProductA() +CreateProductB() +CreateProductB() AbstractProductB Implement operation (create product object) ProductB2 ProductB1 Implement operation (product object) High Performance Computing & Object Technology Laboratory in CSE 6
  • 7. Consequences  Advantages  Isolate concrete classes.  Make exchanging product families easy.  Promote consistency among products.  Disadvantages  Supporting new kinds of products is difficult. High Performance Computing & Object Technology Laboratory in CSE 7
  • 8. Implementation (1/2)  Factories as singletons  Application needs only one instance of a ConcreteFactory  Creating the products  ConcreteProduct define a factory method for each object.  If many product families are possible, the concrete factory can be implemented using the prototype pattern.  Defining extensible factories  Add a parameter to operation that create objects ex) Object make (ObjectType type); High Performance Computing & Object Technology Laboratory in CSE 8
  • 9. Implementation (2/2)  Factory method and Prototype AbstractFactor +CreateProductA() Client +CreateProductB() Prototype (clone) AbstractProductA +clone() ConcreteFactory 1 -ProductA : AbstractProductA -ProductB : AbstractProductB ProductA2 ProductA1 ProductA3 +CreateProductA () +clone() +clone() +clone() +CreateProductB () Factory method AbstractProductB +clone() ProductB2 ProductB1 ProductB3 +clone() +clone() +clone() High Performance Computing & Object Technology Laboratory in CSE 9
  • 10. Sample code (1/5) --- [MazeGame::CreateMaze]-------------------------------------------- Maze *MazeGame::CreateMaze() { Maze *aMaze = new Maze(); Room *r1 = new Room(1); Room *r2 = new Room(2); Door *theDoor = new Door(r1, r2); aMaze->AddRoom(r1); aMaze->AddRoom(r2); // add room r1->SetSide(North, new Wall); // set side r1->SetSide(East, theDoor); r1->SetSide(South, new Wall); r1->SetSide(West, new Wall); r2->SetSide(North, new Wall); r2->SetSide(East, new Wall); r2->SetSide(South, new Wall); r2->SetSide(West, theDoor); return aMaze; }; High Performance Computing & Object Technology Laboratory in CSE 10
  • 11. Sample code (2/5) ---[Class MazeFactory]----------------------------------------------- class MazeFactory { public: MazeFactory(); // Factory method virtual Maze *MakeMaze() const { return new Maze; } virtual Wall *MakeWall() const { return new Wall; } virtual Room *MakeRoom(int n) const { return new Room(n); } virtual Door *MakeDoor(Room *r1, Room *r2) const { return new Door(r1, r2); } }; High Performance Computing & Object Technology Laboratory in CSE 11
  • 12. Sample code (3/5) --- [MazeGame::CreateMaze]-------------------------------------------- // use to MazeFactory Maze *MazeGame::CreateMaze(MazeFactory &factory) { Maze *aMaze = factory.MakeMaze(); Room *r1 = factory.MakeRoom (1); Room *r2 = factory.MakeRoom(2); Door *theDoor = factory.MakeDoor(r1, r2); aMaze->AddRoom(r1); aMaze->AddRoom(r2); r1->SetSide(North, factory.MakeWall()); r1->SetSide(East, theDoor); r1->SetSide(South, factory.MakeWall()); r1->SetSide(West, factory.MakeWall()); r2->SetSide(North, factory.MakeWall()); r2->SetSide(East, factory.MakeWall()); r2->SetSide(South, factory.MakeWall()); r2->SetSide(West, theDoor); return aMaze; } High Performance Computing & Object Technology Laboratory in CSE 12
  • 13. Sample code (4/5) ---[class EnchantedMazeFactory]-------------------------------------- class EnchantedMazeFactory: public MazeFactory { public: EnchantedMazeFactory(); // overrided to factory method virtual Room *MakeRoom(int n) const { return new EnchantedRoom(n, CastSpell()); } virtual Door *MakeDoor(Room *r1, Room *r2) const { return new DoorNeedingSpell(r1, r2); } protected: Spell *CastSpell() const; }; High Performance Computing & Object Technology Laboratory in CSE 13
  • 14. Sample code (5/5) ---[class BombedMazeFactory]-------------------------------------- class BombedMazeFactory: public MazeFactory { public: BombedMazeFactory(); // overrided to factory method virtual Wall *MakeWall() const { return new BombedWall; } virtual Room *MakeRoom(int n) const { return new RoomWithABomb(n); } }; MazeGame game; BombedMazeFactory factory; game.CreateMaze(factory); High Performance Computing & Object Technology Laboratory in CSE 14
  • 15. Related Patterns  Abstract Factory classes are often implemented with Factory method  Abstract Factory and Factory can be implemented using Prototype  A Concrete factory is often a Singleton High Performance Computing & Object Technology Laboratory in CSE 15
  • 16. References [1] Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides: Design Patterns Elements of Reusable Object- Oriented Software. Addison Wesley, 2000 [2] 장세찬 : C++ 로 배우는 패턴의 이해와 활용 . 한빛 미디어 , 2004 [3] Eric Freeman, Elisabeth Freeman, 서환수 역 : Head First Design Patterns. 한빛 미디어 , 2005 High Performance Computing & Object Technology Laboratory in CSE 16