Thursday, February 11, 2016

The Chain of Responsibility Pattern in Dart


How can anyone not love a pattern named chain of responsibility? I mean c'mon, the name invokes all sorts of linked interaction between objects that somehow manage to cooperate on ownership for an action of some sort. It's the kind of thing that makes bureaucracy so awful, but there's a pattern in programming that makes it elegant. So what's not to love?

I start my investigation of the pattern as I so often do, by copying the Java example on the Wikipedia page into lovely Dart code. The prime mover in the pattern—the interface used by the outside world—is the handler. It gets its name, as one might suspect, from its job to… handle a request (and then optionally forward the request on). The handler in the Wikipedia example describes purchasing power.

In Dart, the purchasing power interface looks like:
abstract class PurchasePower {
  PurchasePower _successor;
  void set successor(PurchasePower successor) {
    _successor = successor;
  }

  void processRequest(PurchaseRequest request);
}
The "chain" portion of this pattern is handled by the _successor private variable. If this PurchasePower class does not want to handle the request, the _successor is specified as the next in the chain. The processRequest() method holds the responsibility for handling the request. It receives a purchase request and must decide to handle it or forward the request on to the _successor.

The lowest level of purchasing power in the example is that of a lowly manager:
class ManagerPurchasePower extends PurchasePower {
  final double _allowable = 10 * 1000;

  void processRequest(PurchaseRequest request) {
    if (request.amount < _allowable) {
      print("Manager will approve $request.");
    }
    else if (_successor != null) {
      _successor.processRequest(request);
    }
  }
}

The upper limit that a manager can approve of is $10,000. If the request is for less than that, then the chain ends with the approval by the manager. If it is more than that, then the _successor is then asked to process the same request.

The object being processed by the pattern's handler is a purchase request:

class PurchaseRequest {
  double amount;
  String purpose;
  PurchaseRequest(this.amount, this.purpose);
  String toString() =>
    "\$${amount.toStringAsFixed(2)} for $purpose";
}

It requires a dollar amount and a description of the reason for the purchase. I provide a toString() method so that the entire object can be interpolated in a string (as it is when the manager approves the request).

That is the whole of the pattern. For it to be a true chain, I declare director, VP and presidential purchasing power. Anything that the president, who will be last in succession, cannot purchase needs board approval and not another successor:

class PresidentPurchasePower extends PurchasePower {
  final double _allowable = 60 * 1000;

  void processRequest(PurchaseRequest request) {
    if (request.amount < _allowable) {
      print("President will approve $request");
    }
    else {
      print("Your request for $request needs a board meeting!");
    }
  }
}
In client code, I can create each of these purchasing power objects:
  var manager = new ManagerPurchasePower();
  var director = new DirectorPurchasePower();
  var vp = new VicePresidentPurchasePower();
  var president = new PresidentPurchasePower();
Then I can specify the chain:
  manager.successor = director;
  director.successor = vp;
  vp.successor = president;
Lastly, I can parse the dollar amount being requested and start the chain on its merry path:
  var amount = (args[0] == null) ?
    1000 : double.parse(args[0]);

  var req = new PurchaseRequest(amount, "General Purpose Usage");
  manager.processRequest(req);
With that, I can quickly determine who to bug for the new company automobiles (including my Tesla):
$ ./bin/purchase.dart 5000 
Manager will approve $5000.00 for General Purpose Usage.
$ ./bin/purchase.dart 10000
Director will approve $10000.00 for General Purpose Usage
$ ./bin/purchase.dart 20000
Vice President will approve $20000.00 for General Purpose Usage
$ ./bin/purchase.dart 50000
President will approve $50000.00 for General Purpose Usage
$ ./bin/purchase.dart 75000
Your request for $75000.00 for General Purpose Usage needs a board meeting!

That was a nice start to exploration of the chain of responsibility pattern. I am already looking forward to kicking the tires on this pattern a little more.

Play with the code on DartPad: https://dartpad.dartlang.org/818215777ae57169e6a1.


Day #92

Wednesday, February 10, 2016

Factory Method Pattern and Polymer Paper Elements


I may regret this, but my web-based factory method pattern example lacked a "modern" touch. Well, that's not entirely true, it could add relatively new input elements like number, telephone, and week inputs to a form:



But darn it, what about awesome Paper Elements? Will a <paper-input> element serve as a product of the pattern? It sure would be neat if I could simply drop it into the pattern without many changes.

But alas, it seems that some changes are going to be required. Even though it behaves like an input field, the PaperInput class implements HtmlElement, not InputElement like my FormBuilder class wants:
abstract class FormBuilder {
  // ...
  void addInput() {
    var input = _labelFor(inputElement);
    container.append(input);
  }
  InputElement get inputElement;
  // ...
}
The factory method in this example is the inputElement getter, which returns an InputElement. Because of the PaperElement inheritance, I have to change that to return the more general HtmlElement:
abstract class FormBuilder {
  // ...
  HtmlElement get inputElement;
  // ...
}
How many other changes am I going to have to make?

Well, I certainly have to list Polymer as a dependency in my project's pubspec.yaml. To get <paper-input>, I need paper_elements as well:
name: factory_method_code
dependencies:
  polymer: ">=0.15.1 <0.17.0"
  paper_elements: ">=0.7.0 <0.8.0"
transformers:
- polymer:
    entry_points:
    - web/index.html
Next, I have to import the paper element into the containing page:
<!doctype html>
<html lang="en">
  <head>
    <!-- ... -->
    <link rel="import" href="packages/paper_elements/paper_input.html">
    <script type="application/dart" src="input_factory.dart"></script>
  </head>
  <body><!-- ... --></body>
</html>
I have to do the same with the backing code in the input_factory.dart script:
import 'package:polymer/polymer.dart';
import 'package:paper_elements/paper_input.dart';

abstract class FormBuilder {
  // ...
}
// Concrete factories here...
The final Polymer-y thing that needs to happen is an initPolymer() call in my main() entry point, also in the input_factory.dart script:
main() async {
  await initPolymer();
  // Start up the factory code once Polymer is ready...
}
That's it for the Polymer preliminaries. Now what needs to change in the pattern itself to accommodate PaperInput? Mercifully, not much. In the RandomBuilder class, which is a concrete factory implementation of the FormBuilder, I add a new random option (#5) for PaperInput:
class RandomBuilder extends FormBuilder {
  RandomBuilder(el): super(el);
  Element get inputElement {
    var rand = new Random().nextInt(7);

    if (rand == 0) return new WeekInputElement();
    if (rand == 1) return new NumberInputElement();
    if (rand == 2) return new TelephoneInputElement();
    if (rand == 3) return new UrlInputElement();
    if (rand == 4) return new TimeInputElement();
    if (rand == 5) return new PaperInput();

    return new TextInputElement();
  }
}
Unfortunately, I also have to make a change in the superclass. Previously, when all of the products were InputElement instances, I could count on them supporting the type property (e.g. telephone, number, time), which I could use as a default text label on the page:
abstract class FormBuilder {
  // ...
  _labelFor(el) {
    var text = el.type;
    var label = new LabelElement()
      ..appendText("$text: ")
      ..append(el);

    return new ParagraphElement()..append(label);
  }
}
That will not work for PaperInput, which does not support the type property. If I had control of the product classes, I could force PaperInput to support type. Since that is not possible, I either have to create wrapper classes or, more easily, add an object type test for InputElement:
abstract class FormBuilder {
  // ...
  _labelFor(el) {
    var text = (el is InputElement) ? el.type : el.toString();
    // ...
  }
}

By itself, that one line is not too horrible. That said, I can imagine things going quickly off the rails here by adding a non-InputElement into the mix. For a limited use case like this example, however, it works.

In the end, it was fairly easy to get a PaperInput element added to the mix of my InputElement factory method. Most of the effort was the usual Polymer overhead. The resulting interface mismatch likely will not cause too much trouble in this case, but could get ugly quickly in other scenarios.

Day #91

Tuesday, February 9, 2016

A Nearly Modern Factory Method Pattern


I could make do with the examples of the factory method pattern that I have been using. Still, I would prefer an example that touches the modern web a little closer. Or at least the web. So tonight I try my hand at a venerable, if simple, form builder.

I am not going to worry too much about the details of adding different types of HTML form inputs at this point. To kick things off, I start by adding variations of text input fields to a container. So my Dart abstract creator class declares that it needs to be constructed with a container element:
abstract class FormBuilder {
  Element container;
  FormBuilder(this.container);
}
Next, I declare an addInput() method that will append an input field to the container:
abstract class FormBuilder {
  // ...
  void addInput() {
    var input = _labelFor(inputElement);
    container.append(input);
  }
  // ...
}
The _labelFor() helper method is unimportant in this discussion. It merely adds a text label to the input element. What is important here is the inputElement property. That is going to be the factory method in the factory method pattern. It lacks the usual trailing parentheses because it will be a getter method:
abstract class FormBuilder {
  // ...
  InputElement get inputElement;
  // ...
}
It lacks a method body because the definition of what inputElement does will have to come from subclasses.

Putting these all together, I have a prototypical "creator" in the factory method pattern:
abstract class FormBuilder {
  Element container;
  FormBuilder(this.container);
  void addInput() {
    var input = _labelFor(inputElement);
    container.append(input);
  }
  InputElement get inputElement;
  // ...
}
It declares a factory method, inputElement, and an operation that uses that factory, addInput(). The creator in the classic factory method pattern is an interface for concrete implementations.

For a first pass at a concrete creator class, I declare a RandomBuilder class. As the name implies, the inputElement factory method randomly chooses from a selection of input element types:
import 'dart:math' show Random;

class RandomBuilder extends FormBuilder {
  RandomBuilder(el): super(el);
  InputElement get inputElement {
    var rand = new Random().nextInt(6);

    if (rand == 0) return new WeekInputElement();
    if (rand == 1) return new NumberInputElement();
    if (rand == 2) return new TelephoneInputElement();
    if (rand == 3) return new UrlInputElement();
    if (rand == 4) return new TimeInputElement();
    return new TextInputElement();
  }
}
The other piece of the pattern is the "product." The product in this case the standard InputElement from dart:html — nobody ever said that the product had be a hand-coded class, after all. Given that, the concrete products are the various types of input elements that are randomly returned from the getter factory method.

And there you have it: a simple, web implementation of the factory method pattern!

I can use this in client code by creating a new form builder element as part of a button click handler:
  var button = new ButtonElement()
    ..appendText('Build Input')
    ..onClick.listen((_){
        new RandomBuilder(container).addInput();
      });
This might be a little too simplistic, but I rather like the example. It feels accessible for most web developers. It could also serve as a building block for further examples. I may continue to explore slightly more modern examples tomorrow, though other patterns beckon. Stay tuned!


Play with the code on DartPad: https://dartpad.dartlang.org/ed63a78724e4a8605793.


Day #90

Monday, February 8, 2016

Silly Factories in the Factory Method Pattern


Tonight, I look into using Dart factory constructors in the factory method pattern. Since they both have the word "factory" in them they can probably be used together, right? Well, probably not, but I can no longer resist pairing the two.

Normal generative constructors in Dart behave like constructors in just about any object-oriented language. They create a new instance of the current class, optionally setting some instance variables. Factory constructors, on the other hand, are responsible for building and initializing the object being created. This means that factory constructors can return anything—not limited to the current class.

Take, for instance, a Person class:
class Person {
  int age;
  Person(this.age);
}
When a new Person is instantiated with new Person(21), the generative constructor creates an instance of Person and assigns the age instance variable to 21. Easy peasy.

Now I introduce two subclasses (both still using plain-old generative constructors):
class Child extends Person {
  Child([age=12]) : super(age);
}

class Adult extends Person {
  Adult([age=18]) : super(age);
}
There is nothing special here. Both classes default to an age appropriate for the type of person being created. What these allow me to do is declare a (named) factory constructor back in Person:
class Person {
  factory Person.random() => 
    new Random().nextBool() ? new Child() : new Adult();
}
This Person.random() constructor creates and returns full-blown object. It cannot rely on the language to generate the object, instead it has to do all of the work itself. With that, I can randomly generate children and adults from the Person superclass:
  new Person.random();
  // => Instance of 'Adult'
  new Person.random();
  // => Instance of 'Adult'
  new Person.random();
  // => Instance of 'Child'
What is really weird about these factory constructors is that they do not have to return an instance of the current class or a subclass. Instead, I can declare a Person constructor that returns a string:
class Person {
  // ...
  factory Person.string() { return "A person"; }
}
And that works perfectly fine:
  new Person.random();
  // => Instance of 'Adult'
  new Person.random();
  // => Instance of 'Adult'
  new Person.random();
  // => Instance of 'Child'
  new Person.string();
  // => 'A person'
To be completely honest, that is not "perfectly fine." The Dart type analyzer does complain:
[warning] The return type 'String' is not a 'Person', as defined by the method 'string'
But despite the warning, the code compiles and runs (see this DartPad).

Anyhow, back to the task at hand. How can I use these factory constructors in the factory method pattern? Well, I probably cannot since one is a constructor and the other a method, but let's do it anyway. I currently have a GameFactory class that creates a bunch of different board game products:
class GameFactory {
  // ...
  // The factory method
  createBoardGame([String game]) {
    if (game == 'Checkers') return new CheckersGame();
    if (game == 'Thermo Nuclear War') return new ThermoNuclearWar();
    return new ChessGame();
  }
}
Instead of a factory method, I can use a factory constructor:
class GameFactory {
  // ...
  factory GameFactory.createBoardGame([String game]) {
    if (game == 'Checkers') return new CheckersGame();
    if (game == 'Thermo Nuclear War') return new ThermoNuclearWar();
    return new ChessGame();
  }
}
Since BoardGame is not a subclass of GameFactory, the Dart type analyzer complains something fierce about this. But it compiles and runs anyway:
  new GameFactory.createBoardGame('Checkers').play();
  new GameFactory.createBoardGame('Thermo Nuclear War').play();
  new GameFactory.createBoardGame().play();
So what does this buy me? Like war, absolutely nothing.

In fact, I lose the ability to associate the factory constructor board games with the rest of the series. Each of those three board games are completely independent of the game factory series, which can no longer keep a reference to each for a final score:
  var series = new GameFactory('Professor Falken', 'Joshua');
  series.start();

  new GameFactory.createBoardGame('Checkers').play();
  new GameFactory.createBoardGame('Thermo Nuclear War').play();
  new GameFactory.createBoardGame().play();
So in the end, factory constructors and the factory method pattern are amusing together, but I can see no practical benefit. It was still totally worth messing around with them though!

Play with the amusing code on DartPad: https://dartpad.dartlang.org/4a59d56472d11cde9354.


Day #89

Sunday, February 7, 2016

Factory Games with Mirrors


Up tonight I finally carry through on my threat to apply mirrors to the factory method pattern in Dart. I am unsure if my beloved mirrors can have their usual improving effect (in my eyes at least), but I am always happy to have an excuse to play with reflection and mirrors.

Tonight's excuse comes in the form of the language specific implementations mentioned in the Gang of Four book. They mentioned that factory methods in Smalltalk often return the class to be created instead of an object. Aside from having to import the dart:mirrors library, it is not much more difficult to do the same thing in Dart.

The prime mover in the factory method pattern is the creator class. In the "game factory" example with which I have been toying, the GameFactory class creates a series of games between two players, then allows them chose any number of board games to play. The returns-a-class version might look something like:
// Creator
class GameFactory {
  String playerOne, playerTwo;
  GameFactory(this.playerOne, this.playerTwo);
  // ...

  // The factory method
  Type boardGameClass([String game]) {
    if (game == 'Checkers') return CheckersGame;
    if (game == 'Thermo Nuclear War') return ThermoNuclearWar;
    return ChessGame;
  }
}
That will force the client code to reflect on the classes, which is an obnoxious thing to ask of client code. So instead, I import dart:mirrors and return a class mirror from the boardGameClass() method:
import 'dart:mirrors' show reflectClass, ClassMirror;

// Creator
class GameFactory {
  // ...
  ClassMirror boardGameClass([String game]) {
    if (game == 'Checkers') return reflectClass(CheckersGame);
    if (game == 'Thermo Nuclear War') return reflectClass(ThermoNuclearWar);
    return reflectClass(ChessGame);
  }
}
Let's take a look at the resulting client code next. When it worked directly with objects, the client code looked like:
main() {
  var series = new GameFactory('Professor Falken', 'Joshua');
  series.start();

  var game;
  game = series.createBoardGame('Checkers');
  game.play();

  game = series.createBoardGame('Thermo Nuclear War');
  game.play();

  // Defaults to a nice game of chess
  game.createBoardGame();
  game.play();
}
That is pretty simple: start by creating a game factory instance, then create a game / play the game, create a game / play a game, etc.

With mirrors, the code now becomes:
main() {
  var series = new GameFactory('Professor Falken', 'Joshua');
  series.start();

  var game;
  game = series.
    boardGameClass('Checkers').
    newInstance(new Symbol(''), []).
    reflectee;
  game.play();

  game = series.
    boardGameClass('Thermo Nuclear War').
    newInstance(new Symbol(''), []).
    reflectee;
  game.play();

  // Defaults to a nice game of chess
  game = series.
    boardGameClass().
    newInstance(new Symbol(''), []).
    reflectee;
  game.play();
}
Look, I love mirrors more than just about anyone, but even I have to admit that is horrible. There is far too much noise obscuring the relatively simple intent of the code. I am not a fan of being forced to supply a constructor as a Symbol—it seems like the default constructor could be inferred (I'm sure there is a good reason it is not though). Similarly, I do not like being forced to supply an empty list of arguments to the newInstance() constructor method. But the truth is, even if both of those complaints went away, the newInstance() and reflectee calls would still make a mirror approach significantly less desirable than the plain-old object approach.

So mirrors are always undesirable in the factory method pattern, right? Well, not so fast. If there is a situation in which the client might want to create products with varying constructor arguments, then this mirror approach could come in handy. For instance, if we want to teach Joshua about thermonuclear war, we can create a alternate constructor for assigning different starting values for the two players:
class ThermoNuclearWar extends BoardGame {
  List playerOnePieces = [ '1,000 warheads' ];
  List playerTwoPieces = [ '1,000 warheads' ];
  ThermoNuclearWar(): super();
  ThermoNuclearWar.withWarheads(this.playerOnePieces, this.playerTwoPieces);
  String get winner => "None";
}
The client code can then run through as many scenarios as it takes to teach that thermonuclear war is a very strange game indeed:
  game = series.
    boardGameClass('Thermo Nuclear War').
    newInstance(new Symbol(''), []).
    reflectee;
  game.play();

  game = series.
    boardGameClass('Thermo Nuclear War').
    newInstance(
      new Symbol('withWarheads'),
      [['1 warhead'], ['1 warhead']]
    ).
    reflectee;
  game.play();

  game = series.
    boardGameClass('Thermo Nuclear War').
    newInstance(
      new Symbol('withWarheads'),
      [['1 warhead'], ['1,000 warheads']]
    ).
    reflectee;
  game.play();
This would result in output like:
$ ./bin/board_game.dart
*** Professor Falken vs. Joshua ***

  ThermoNuclearWar
    Player One starts with: 1,000 warheads
    Player Two starts with: 1,000 warheads
    --
    Winner: None

  ThermoNuclearWar
    Player One starts with: 1 warhead
    Player Two starts with: 1 warhead
    --
    Winner: None

  ThermoNuclearWar
    Player One starts with: 1 warhead
    Player Two starts with: 1,000 warheads
    --
    Winner: None
Afterwards, the game series can then switch back to a nice game of chess:
  // Defaults to a nice game of chess
  game = series.
    boardGameClass().
    newInstance(new Symbol(''), []).
    reflectee;
  game.play();
So there is a reason for using mirrors in the factory method pattern after all. Yay! That said, they do not make as much sense as returning classes in Smalltalk. I will have to continue my search for Dart-specific features that can be brought to bear on the factory method pattern tomorrow.

Play with the code on DartPad: https://dartpad.dartlang.org/d2a79f59113c888d0788.


Day #88

Saturday, February 6, 2016

I've Got a Factory in My Factory in My Class Hierarchy of Factories (or Something Like That)


Yesterday I worked up a Dart example of the factory method pattern in which a "game factory" could pit two players against each other in a series of board games:
main() {
  var series = new GameFactory('Professor Falken', 'Joshua');

  series
    ..start()
    ..createBoardGame('Checkers').play()
    ..createBoardGame('Thermo Nuclear War').play()
    ..createBoardGame().play();
}
Most of the concrete implementation of the pattern is placeholder print() statements. The code so far establishes a series of games between two players, creates a board game via the factory method from which the pattern gets its name, then plays the game. Currently, this results in output along the lines of:
$ ./bin/board_game.dart
*** Professor Falken vs. Joshua ***
  CheckersGame
    Player One starts with: 12 pieces
    Player Two starts with: 12 pieces
    --
    Winner: Player One

  ThermoNuclearWar
    Player One starts with: 1,000 warheads
    Player Two starts with: 1,000 warheads
    --
    Winner: None

  ChessGame
    Player One starts with: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
    Player Two starts with: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
    --
    Winner: Player One
That seems a decent example of the pattern except that the placeholder code is starting out with ugliness. Specifically, the products in the patterns—the various board games—are on the repetitive side:
class ChessGame extends BoardGame {
  List playerOnePieces = [
    '1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
  ];
  List playerTwoPieces = [
    '1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
  ];
}
What the various BoardGame classes need is a common way to create the initial set of pieces on the board. If only there were a design pattern that could help with that…

Say, that sounds like a factory method pattern! Now, I know what you're thinking, a factory inside a factory—that's typical pattern fanboyism. I'm not going to argue with you, but I beg your patience for just a bit...

If BoardGame is now a factory, I need it to declare a factory method for its subclasses to implement. Since it needs to generate game pieces for the start of a game, I have it require a _createPieces() method:
abstract class BoardGame {
  GamePieces playerOnePieces, playerTwoPieces;
  BoardGame() {
    playerOnePieces = _createPieces();
    playerTwoPieces = _createPieces();
  }
  GamePieces _createPieces();
  // ...
}
Both player one and player two will be assigned the same number of pieces to begin, so the constructor assigns both player one's and player two's pieces to the results of the _createPieces factory method. But the abstract BoardGame does not know how to create chess, checkers, etc. pieces. Subclasses need to define these:
class ChessGame extends BoardGame {
  GamePieces _createPieces() => new ChessPieces();
}

class CheckersGame extends BoardGame {
  GamePieces _createPieces() => new CheckersPieces();
}

class ThermoNuclearWar extends BoardGame {
  GamePieces _createPieces() => new ThermoNuclearPieces();
  String get winner => "None";
}
With that, my board game classes are significantly DRYer and better able to define the functionality behind the actual game play.

But back to the factory-in-a-factory craziness that I have inflicted on myself. I think it actually makes sense. From an illustrative standpoint, it is over the top, but it feels like a reasonable, organic structure. Perhaps last night's GameFactoryGameBoard creator/product was somewhat artificial, but I need to generate different gameboards at runtime, so that makes a decent amount of sense. If anything, tonight's approach feels even better. Each boardgame needs to layout and assign pieces to the players, so a factory method serves nicely in that capacity.

In fact, it makes so much sense that it is a flavor of the factory method pattern: the parallel class hierarchy variation. By taking this approach, I know that, for each type of board game in the BoardGame class hierarchy, there will be a corresponding entry in the hierarchy of the GamePieces classes. The ChessGame needs to use ChessPieces in order to populate the game:
class ChessGame extends BoardGame {
  GamePieces _createPieces() => new ChessPieces();
}
Armed with that knowledge, the client code can make use of this as well. For example it could restart a game or start a new one:
  series.start();
  var game;
  game = series.createBoardGame('Checkers');
  game.play();
  // Start over
  game.playerOnePieces = game._createPieces();
  game.playerTwoPieces = game._createPieces();
  game.play();
That might be a little more useful in another example (a restart() method would make most sense in this example), but it still serves to illustrate some of the potential of this parallel hierarchy approach. I may examine a different example tomorrow to get a better handle on this. Or I may switch to mirrors. Either way, it is sure to be more fun with factories!

Play with the code on DartPad: https://dartpad.dartlang.org/639e49cfc1b2ee3cb82a.


Day #87

Friday, February 5, 2016

Factory Method without Factory Subclasses


I am already bored by the factory method pattern. Time for Dart mirrors! I kid of course. About the bored, not the mirrors. I goes without saying that I'm going to add mirrors.

The Gang of Four book mentions two major varieties of the pattern: one that uses an abstract class, forcing subclasses to define the factory implementations, and the other in which the creator class provides a default factory implementation. I tried the the former last night, so tonight I try with a default implementation.

For this example, I adopt the Delphi example on the Wikipedia page, which describes a game factory. For this example, two players want to play a series of games against each other. The creator for that might look like:
// Creator
class GameFactory {
  String playerOne, playerTwo;
  GameFactory(this.playerOne, this.playerTwo);
  String toString() => "*** $playerOne vs. $playerTwo ***";

  // The factory method
  BoardGame createBoardGame([String game]) {
    if (game == 'Checkers') return new CheckersGame();
    if (game == 'Thermo Nuclear War') return new ThermoNuclearWar();
    return new ChessGame();
  }
}
The constructor requires the names of both players. Once they are ready to play a game, they might choose a game from a text based listing of games, passing the name to createBoardGame(). In this example, there are no subclasses for the creator—the GameFactory knows how to create all products.

The "products" in this version of the pattern are different board games that can be played in the system. Each will need a list of pieces that can be played:
// Product
class BoardGame {
  List playerOnePieces = [];
  List playerTwoPieces = [];

  String get winner => new Random().nextBool() ? 
    "Player One" : "Player Two";
  String toString() =>
    "  ${this.runtimeType}\n"
    "    Player One has: ${playerOnePieces.join(', ')}\n"
    "    Player Two has: ${playerTwoPieces.join(', ')}\n"
    "    Winner: $winner\n";
}
So a chess game would look like:
class ChessGame extends BoardGame {
  List playerOnePieces = [
    '1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
  ];
  List playerTwoPieces = [
    '1 king', '1 queen', '2 rooks', '2 bishops', '2 knights', '8 pawns'
  ];
}
There is some redundancy there, but I will worry about that another time. For now, I have my single creator class and various product classes. Which means that I am ready for some client code.

I start with the creator, which starts the game series between two players:
  var series = new GameFactory('Professor Falken', 'Joshua');
  print(series);
Then they can play various games, choosing each from the text listing on the main menu:
  game = series.createBoardGame('Checkers');
  print(game);

  game = series.createBoardGame('Thermo Nuclear War');
  print(game);

  game = series.createBoardGame();
  print(game);
Running this would result in something like the following output:
$ ./bin/board_game.dart
*** Professor Falken vs. Joshua ***
  CheckersGame
    Player One has: 12 pieces
    Player Two has: 12 pieces
    Winner: Player Two

  ThermoNuclearWar
    Player One has: 1,000 warheads
    Player Two has: 1,000 warheads
    Winner: None

  ChessGame
    Player One has: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
    Player Two has: 1 king, 1 queen, 2 rooks, 2 bishops, 2 knights, 8 pawns
    Winner: Player One
So there you go: a factory method pattern example in which the creator is a concrete class, provided a default product, and can supply all products. It does not feel terribly different from last night's example. In fact, it feels almost too simple to warrant the creator class. Except for the need to remember the two players' names, this could almost be done in client code.

I am unsure if this is the example that I would like to use in Design Patterns in Dart as it is a tad simplistic. Then again, there are some opportunities for improving the code that may make it more illustrative. That's something for tomorrow. Plus mirrors!

Play with the code on DartPad: https://dartpad.dartlang.org/0018524156ade602d043.


Day #86