Saturday, January 9, 2016

A Simple Proxy Pattern in Dart

I start my exploration of the proxy pattern tonight by looking at the protection version of the pattern. I rather like the simplicity of the example used on the Wikipedia page, so I start there, adapting the code to Dart.

The subject of this example is an Automobile which can be driven:
// Subject
abstract class Automobile {
  void drive();
The proxy and real subjects will implement this (simple) interface. The real subject, a Car, includes possibly scary business logic that should be kept out of irresponsible hands:
// Real Subject
class Car implements Automobile {
  void drive() {
    print("Car has been driven!");
The proxy subject is where the action takes place. The constructor requires a Driver, which will be used to determine of the real subject needs protection:
// Proxy Subject
class ProxyCar implements Automobile {
  Driver _driver;
  Car _car;

  ProxyCar(this._driver) {
    _car = new Car();
  // ...
In addition to storing the driver, the constructor also creates an instance of the real subject. Neither the driver nor the real subject need to be accessed from outside the class, so both are declared private.

Last up, I implement the drive() from the Automobile interface. If the driver is too young, then access is denied, otherwise the drive() method on the real subject is invoked:
// Proxy Subject
class ProxyCar implements Automobile {
  // ...
  void drive() {
    if (_driver.age <= 16) {
      print("Sorry, the driver is too young to drive.");
And that is all there is to the protection proxy. Client code can create an instance of the ProxyCar for an underage driver and a proper age drive, trying to drive both:
  Automobile car;

  // Proxy will deny access to real subject
  print("* 16 year-old drive here:");
  car = new ProxyCar(new Driver(16));;

  // Proxy will allow access to real subject
  print("* 25 year-old drive here:");
  car = new ProxyCar(new Driver(25));;
With that, one car is prevented from being driven while the other works fine:
$ ./bin/drive.dart
* 16 year-old drive here:
Sorry, the driver is too young to drive.

* 25 year-old drive here:
Car has been driven!
And there you go, a simple protection proxy pattern implementation in a few lines of Dart.

Play with the code on DartPad:

Day #59

No comments:

Post a Comment