Rusty Divine

Live, Love, Learn, Teach

Learning Design Patterns – Command Pattern

This week I'll be taking charge of the Command Pattern in my series on design patterns plucked fromthis book and from examples on the Internet.

What is it?

A simple analogy for the Command Pattern is a remote control. When you are clicking through your 637 channels looking for something in English that isn't tying to sell you something or change your political or religious point of view, you're giving commands to your remote, which then tells the system to increment the channel by one.

And when you use a universal remote and set your TV to channel 3, your VCR to channel F1, your sound system to Video, and then turn on your DVD player to watch a movie you rented from Blockbuster because nothing is on TV; your remote is issuing commands like "On" to each device, and the device is responsible for taking care of the details of turning itself on. If your remote was hardwired to turn on each component, you would have to open it up and add more code each time you switched out one TV for another – that's tightly coupled!

The Command Pattern can include more than just the ability to encapsulate requests; it can also queue up commands and log them, and support an "Undo" operation. By extending the pattern slightly, you can also create the ability to run a macro command that executes several commands at once – imagine a universal remote that has an "all-on" button that turns all of your devices on at once.

Where is it used?

This week I'd like to try something new for this section. I'd like you to add a comment to say where you've seen or used the Command Pattern – I'd enjoy hearing some real world scenarios, and it would help illuminate the pattern for everyone.

But why?

One of the fundamental rules of good design is to not have to open up old code to change it because it can result in unexpected consequences. The Command Pattern helps you extend your code by encapsulating method invocations, allowing you to add new objects that implement the command interface without having to monkey around with existing code and adding methods to control the new objects.

OK, and how is it implemented?

//Java
//Create a TV class that knows how to turn itself on and off
public class TV() {
	public TV() {
		system.out.println("TV Created");
	}

	public on() {
		system.out.println("TV On");
	}

	public off() {
		system.out.println("TV Off");
	}
}

// The command interface will be implemented by the command objects
public interface Command {
	public void execute();
	public void undo();
}

// Add a command for turning the TV on
public class TVOnCommand implements Command {
	TV tv;

	public TVOnCommand(TV tv){
		this.tv = tv;
	}

	public void execute() {
		tv.on();

	}

	public void undo() {
		tv.off()
	}
}
 
// Add a command for turning the TV off
public class TVOffCommand implements Command {
	TV tv;

	public TVOffCommand(TV tv){
		this.tv = tv;
	}

	public void execute() {
		tv.off();
	}

	public void undo() {
		//undo the off by turning back on
		tv.on()
	}
}

// Create a simple remote
public class SimpleRemote {
	Command onButton;
	Command offButton;
	Command undoCommand;

	public SimpleRemote() {}

	public void setOnCommand(Command command) {
		onButton = command;
	}

	public void setOffCommand(Command command) {
		offButton = command;
	}

	// The remote doesn't care what device it's turning on, it just issues the command

	// set the undo command object to the last object called
	public void buttonOnWasPressed() {
		onButton.execute();
		undoCommand = onButton;
	}

	public void buttonOffWasPressed() {
		offButton.execute();
		undoCommand = offButton;
	}

	public void buttonUndoWasPressed() {
		undoCommand.undo();
	}
}

public class RemoteTest {

	public static void main(String[] args) {
		SimpleRemote remote = new SimpleRemote();
		TV tv = new TV();
		TVOnCommand tvOn = new TVOnCommand(tv);
		TVOffCommand tvOff = new TVOffCommand(tv);

		//program the remote to turn the TV on and off
		remote.setOnCommand(tvOn);
		remote.setOffCommand(tvOff);

		remote.buttonOnWasPressed();
		remote.buttonOffWasPressed();
 
		//turn the TV back on by undoing the off call
		remote.buttonUndowWasPressed();
	}
}

//To implement a macro command that can turn on all devices, e.g.
public class MacroCommand implements Command {
	Command[] commands;

	public MacroCommand(Command[] commands) {
		this.commands = commands;
	}
 
	public void execute() {
		for (int i = 0; i < commands.length; i++) {
			commands[i].execute();
		}
	}

	public void undo() {
		for (int i = 0; i < commads.length; i++) {
			commands[i].undo();
		}
	}
}

Learning Design Patterns - Decorator Pattern

This week I'll be hanging the Decorator Pattern in my series on design patterns plucked from this book and from examples on the Internet.

What is it?
An important design rule is to design your code to be open for extension, but closed for modification, and the Decorator Pattern is one way to go about extending existing code. The decorator wraps up an existing object and then adds functionality to it; and since the decorator is of the same type as the object it wraps, the effect should be seamless for client code (unless client code is relying on the concrete type of the original object).

Where is it used?
The Decorator Pattern is used to extend existing code without modifying it and to create a highly configurable design that relies less on inheriting behaviors and more on composition.
The pattern has some potential downsides. Applying it can result in a lot of small classes that can confuse someone new to the code, can cause type errors if the client code is relying on the concrete class that is wrapped up in the decorator objects, and it adds some complexity when trying to initiate components.
Targeting the areas of your application that are most prone to change would be a good start to considering where to apply this pattern.

But why?
Why not just add instance variables to a superclass, then use inheritance to set their values in sub classes? If those instance variables are not going to grow or change over time you could opt for simplicity in design over extensibility. The Decorator Pattern can help when those attributes are going to fluctuate; it can provide a way to extend the functionality without touching the existing code, which will reduce the chance of unintended consequences.

OK, and how is it implemented?

//Java
public abstract class EscortService {
	String description = "Unknown Service";
	public String getDescription() {
		return description;
	}
	public abstract double cost();
}
// create the decorator
public abstract class EscortServiceDecorator extends EscortService {
	public abstract string getDescription();
}
// create the concrete classes 
public class Monica extends EscortService {
	public Monica() {
		description = "Monica, a beautiful brunette";
	}
	public double cost() {
		return 350.00;
	}
}
public class Charlie extends EscortService {
	public Charlie() {
		description = "Charlie, a former Chipendale Dancer";
	}
	public double cost() {
		return 169.00;
	}
}
// create the decorations
public class Dinner extends EscortService {
	EscortService es;
	public Dinner(EscortService es) {
		this.es = es;
	}
	public string getDescription() {
		return es.getDescription() + ", have dinner";
	}
	public double cost() {
		//add on to base fee
		return 45.00 + es.cost();
	}
}
public class Nightcap extends EscortService {
	EscortService es;
	public Nightcap(EscortService es) {
		this.es = es;
	}
	public string getDescription() {
		return es.getDescription() + ", have a nightcap";
	}
	public double cost() {
		//add on to base fee
		return 95.00 + es.cost();
	}
}

// Example use
public class RandysEscorts {
	//could use factory pattern to decouple "Monica" use
	EscortService es = new Monica();
	//prints: Monica, a beautiful brunette $350.00
	System.out.println(es.getDescription() + " $" + es.cost();
	
	//Add dinner and a nightcap
	es = new Dinner(es);
	es = new Nightcap(es);
	//prints: Monica, a beautiful brunette, have dinner, have a nightcap $490.00
	System.out.println(es.getDescription() + " $" + es.cost();
}
	

Learning Design Patterns - Factory Pattern

This week I'll be manufacturing the Factory Pattern in my series on design patterns plucked from this book and from examples on the Internet.

What is it?
The factory pattern comes in a few flavors; the simple factory, the factory method, and the abstract factory patterns. Regardless of the implementation, the goal of the factory pattern is to encapsulate object creation so that the design isn't as dependant on concrete classes. By relying less on instantiating concrete classes, common code can remain untouched when those classes undergo changes.

The simple factory isn't actually a pattern; it's more of a design principle. The simple factory encapsulates the object creation code, but keeps control over how the object is created. Simple factories are often designed as a class with a static method (aka static factory) that returns the object requested.

The factory method pattern takes the simple factory one step further by becoming an abstract class that has an abstract method for instantiating the object (at least usually; they don't have to be abstract if there is only one object type). Subclasses then inherit from the factory and are responsible for actually creating the object, in what is commonly referred to as deciding how to instantiate the object (it really just means the factory doesn't know or care what object is being returned). The factory often uses the returned object to perform other tasks.

The abstract factory pattern enforces the Dependency Inversion Principle (Impress your peers with that one)! Simply stated, that means the design should depend on abstractions over concrete classes; no variable should hold a reference to a concrete class, no class should derive from a concrete class, and no method should override an implemented method of its base classes. This, of course, is impossible to enforce completely in an application of any significant complexity, but it is a guiding principal. The abstract factory pattern groups like objects together by providing an interface to them without specifying their concrete classes.

Where is it used?
Anywhere new objects are being instantiated with the 'new' keyword, or however it is done in the language being used.

But why?
The factory patterns reduce common code's dependency on instantiating objects with the 'new' keyword. By programming to abstractions instead, the code achieves loose coupling – i.e., it is less dependant on the design of the concrete classes.

OK, and how is it implemented?

In Ruby:

In .Net:

In Java:

// Simple factory
public class SimpleWidgetFactory {
	public Widget createWidget(String type) {
		Widget w = null;
		//handle the creation details here
		if (type.equals("rubber")) {
			w = new RubberWidget();
		}
		return w;
	}
}

// Factory Method
public abstract class WidgetFactory {
	public Widget orderWidget(String type) {
		Widget w;
		w = createWidget(type);
		return w;
	}
	//let the subclass that implements this decide how
	//to create the widget
	protected abstract Widget createWidget(String type);
}

// Abstract Factory pattern
//First, create the interface for the factory
public interface WidgetIngredientFactory {
	public Tar createTar();
	public Spring createSpring();
}
//implement the factory in one or more different ways
public class DurableWidgetIngredientFactory  implements WidgetIngredientFactory {
	public Tar createTar() {
		return new ThickTar();
	}
	public Spring createSpring(); {
		return new TiggerSpring();
	}
}
public class WeakWidgetIngredientFactory implements WidgetIngredientFactory {
	public Tar createTar() {
		return new LiquidTar();
	}
	public Spring createSpring() {
		return new RustedSpring();
	}
}

//The factory depends on this abstract class, and the 
//sub classes depend on this abstract class
public abstract class Widget {
	Tar tar;
	Spring spring;
	abstract void prepare();
void Dodad() {
	System.out.println("Widget dodad");
}
}

//Now, look at the actual widget subclass
public class MyWidget extends Widget {
	WidgetIngredientFactory wf;
	public MyWidget(WidgetIngredientFactory wf) {
		//pass in the factory type, like DurableWidgetIngredientFactory
		this.wf = wf;
	}
	void prepare() {
		//the factory now takes care of creation!
		tar = wf.createTar();
		spring = wf.createSpring();
	}
}

Learning Design Patterns - Strategy Pattern

This week I’ll be subscribing to the Strategy Pattern in my series on design patterns plucked from this book and from examples on the Internet.

What is it?
The Strategy Pattern defines a family of behaviors, or algorithms, encapsulates each one, and makes them interchangeable.

Where is it used?
An example of when the Strategy Pattern is used would be for grouping different sorting algorithms. A super class could be created that has a sorting behavior defined as a sorting interface, which delegates the sorting. A sub class that extends the super class and when the inherited sort behavior is called (sub.sort), the sub class can call a specific sort algorithm. Furthermore, if the super class allows the sort behavior to be set at runtime, the sort behavior can be changed dynamically.

But why?
The Strategy Pattern increases flexibility by allowing the algorithms to vary independently from the classes that use them. New algorithms can be added, and the existing classes can then take advantage of them without changing any of their code.

OK, and how is it implemented?

public abstract class Student {

	//Declare the two reference variables for
	//the behavior interface types
	IGotoClass gotoClassBehavior;
	IDrink drinkBehavior;
	
	public Student() {}

	//All students will dress for class
	public abstract void display();


	//delegate the Student behaviors; this is
	//an example of using composition, which
	//should be favored over inheritence because
	//it increases flexibility by allowing
	//the class to change at runtime.
	public void GotoClass() {
		//delegate GotoClass behavior
		gotoClassBehavior.gotoClass();
	}

	public void Drink() {
		//delegate Drink behavior
		drinkBehavior.drink()
	}

	//Add setBehavior's so that the class
	//can be changed at runtime.
	public void setGotoClassBehavior(IGoToClass gtc) {
		gotoClassBehavior = gtc;
	}

	public void setDrinkBehavior(IDrink db) {
		drinkBehavior = db;
	}
}

//Create the interfaces

public interface IGotoClass {
	public void gotoClass();
}

public interface IDrink {
	public void drink();
}


//Goto class behaviors (add more as needed)

public class GotoClassOnBike implements IGotoClass {
	public void gotoClass() {
		System.out.println("I'm riding my bike");
	}
}

public class GotoClassNot implements IGotoClass {
	public void gotoClass() {
		system.out.println("I'm hungover; not going
		to class today.");
	}
}

//Drinking behaviors (add more as needed)

 public class DrinkNot() {
	public void drink() {
		system.out.println("I don't drink");
	}
}

//NOTE: The DrinkTons class is also used by the Circus Clown class;
//this code benifits from reuse without the baggage of 
//inheritence
public class DrinkTons() {
	public void drink() {
		system.out.println("I'm a lush");
	}
}


//Student Simulator

public class GoodStudent extends Student {
	gotoClassBehavior = new GotoClassOnBike();
	drinkBehavior = new DrinkNot();	
}

public Class BadStudent extends Student {
	gotoClassBehavior = new GotoClassNot();
	drinkBehavior = new DrinkTons();
}

public class miniStudentSimulator {
	public static void main(String[] args) {
		//Create a new student while programming to the 
		//Student supertype to exploit polymorphism
		Student goodyTwoShoes = new GoodStudent;
		
		//Call the GoodStudent's inherited behavior's
		//which then delegate to the GoodStudent specific
		//behaviors; i.e, don't drink and go to class
		goodyTwoShoes.Drink();
		goodyTwoShoes.GotoClass();

		//Now, corrupt the student by drinking and skipping class
		goodyTwoShoes.setDrinkBehavior(new DrinkTons());
		goodyTwoShoes.setGotoClassBehavior(new GoToClassNot());
                //the student is now corrupted and will drink tons and not goto class
                goodyTwoShoes.Drink();
		goodyTwoShoes.GotoClass();
	}
}

Learning Design Patterns - Observer Pattern

This week I’ll be subscribing to the Observer Pattern in my series on design patterns plucked from this book and from examples on the Internet.

What is it?
The Observer Pattern helps keep your objects in the know; i.e., communicating with other objects about important events.

The pattern is analogous to a newspaper company and its subscribers. Say one day your power gets turned off by the electric utility since you haven’t paid your bill for six months (this actually happened to me one time; it was the first apartment my wife and I lived in and I assumed that the power would be transferred over to me and I’d get a bill. Evidently I needed to call the utility and subscribe, and since I didn’t, they figured I was Freddy the Freeloader and cut off my juice). When your power is cut off, you realize pretty quickly how dependant you are on it for everything from your electric can opener to your TV, and especially to the Internet. So, jonesing for some news, you call up the newspaper company and subscribe to the paper (it will be at least another 6 months before they realize you can’t pay, and by that time you should have your electricity back anyway). The newspaper company adds you to their list of subscribers, and lo-and-behold the next morning you’re awaken to the thunderous bang of a paper propelled into your front door by a kid with major-league hopes. In fact, every time the newspaper publishes a paper, they make sure you get one as long as your on their list. And when you cancel your account, or they revoke your subscriptions for lack of funds, they’ll take you off their list of subscribers and you’ll stop getting the paper when they publish it.

That’s pretty much it. There’s a publisher, sometimes called the "Subject" and subscribers, also called "Observers". There are a few different ways to implement the pattern, though, like whether the publisher just notifies subscribers of changes, or whether it allows subscribers to get part or all of the data by themselves, or some of both.

Where is it used?
To maintain state and notify other objects of changes. Some examples include a stock-ticker application, weather data service, and machine health and status (e.g., CPU temp, fan speed, etc.).

But why?
Letting the publisher control the data in one place, and then notify any interested subscriber objects when that data changes, is cleaner than controlling the data in each potential subscriber object and separately updating each when that data changes.

The relationship between the publisher and subscriber is described as "loose coupling" because they do interact, but they aren’t so dependant on one another that changing one will affect the other. All that matters to the publisher is that the subscriber implements an observer interface, and all that matters to the subscriber is that the publisher implements a subject interface. The loosely coupled relationship minimizes dependencies, and promotes a flexible design.

OK, and how is it implemented?
The publisher and subscriber each need to implement an interface; to notify and update, respectively.

// Publisher interface
public interface IPublisher {
	public void registerSubscriber(ISubscriber subscriber);
	public void removeSubscriber(ISubscriber subscriber);
	public void notifySubscribers();
}

// Subscriber interface
public interface ISubscriber {
	public void update();
}

//Publisher
public class JournalStarNews implements IPublisher {
	private ArrayList subscribers;
	private string news;

	public JournalStarNews() {
		subscribers = new ArrayList();
	}

	public void registerSubscriber(ISubscriber subscriber) {
		subscribers.add(subscriber);
	}

	public void removeSubscriber(ISubscriber subscriber) {
		int i = subscribers.indexof(subscriber);
		if (i >= 0) {
			subscribers.remove(i);
		}

	public void notifySubscribers() {
		for (int i = 0; i < subscribers.size(); i++) {
			ISubscriber subscriber = (ISubscriber)subscribers.get(i);
			subscriber.update();
		}

	public void hotOffThePress(string News) {
		news = News;
		notifySubscribers();
		}

	public string getNews() {
		return news;
		}

}

//Subscriber
public class NewspaperReader implements ISubscriber {
	private string news;
	private IPublisher JournalStarNews;

	public NewspaperReader(IPublisher JournalStarNews) {
		this.JournalStarNews = JournalStarNews;
		JournalStarNews.registerSubscriber(this);
	}

	public void update() {
		this.news = JournalStarNews.getNews();
	}
}