© O. Nierstrasz, O. Greevy, A. Kuhn P2 — Clients and Servers 8.1 Roadmap Generics Abstract Factory Annotations Model-Driven Engineering
© O. Nierstrasz, O. Greevy, A. Kuhn P2 — Clients and Servers 8.2 Design Patterns, a preview… “Each pattern describes a problem which occurs over and over again in our environment; and it describes the core of the solution to that problem, in such a way that you can use this solution a million times over…” — Christopher Alexander
© O. Nierstrasz, O. Greevy, A. Kuhn P2 — Clients and Servers 8.3 Creational Patterns … deal with the best way to create objects
© O. Nierstrasz, O. Greevy, A. Kuhn P2 — Clients and Servers 8.4 Abstract Factory Pattern >A Factory is the location in the code at which objects are created. >Provides an interface for creating families of related dependent objects. >Let clients create products in any family of products in an abstract way, without having to specify their concrete class. >Separates the details of implementation of a set of objects from its general usage.
© O. Nierstrasz, O. Greevy, A. Kuhn P2 — Clients and Servers 8.5 Structure of the Abstract Factory Pattern AbstractFactory createProduct() ConcreteFactory1 createProduct() ConcreteFactory2 createProduct() Client AbstractProduct concreteProduct
© O. Nierstrasz, O. Greevy, A. Kuhn P2 — Clients and Servers 8.6 Abstract Factory with Generics: Ludo Example package ludo; // NOTE interface for "Abstract Factory" pattern. public interface Factory { public T createInstance(); }
© O. Nierstrasz, O. Greevy, A. Kuhn P2 — Clients and Servers 8.7 The Concrete Factory package ludo; public class LudoFactory implements Factory { … public Ludo createInstance() { initializeHome(); initializeBranchings(); initializeMainRing(quarterLength); initializeHomeRuns(quarterLength); initializeNests(); return new Ludo(nest); } … We specify the type to be Ludo
© O. Nierstrasz, O. Greevy, A. Kuhn P2 — Clients and Servers 8.8 The Ludo Example «interface» AbstractFactory createInstance() : T LudoFactory createInstance() : Ludo Ludo «interface» Board addPlayer(Player ) …
© O. Nierstrasz, O. Greevy, A. Kuhn P2 — Clients and Servers 8.9 The Client drives the Ludo Game public class Driver implements Runnable { private Board board; public Driver(Factory factory) { this.board = factory.createInstance(); board.addPlayer(new Player()); } … public class Main { public static void main(String[] args) { Runnable gameDriver = new Driver(new LudoFactory()); gameDriver.run(); } We specify the Game Factory we want The Driver can drive any Board game