Rusty Divine

Live, Love, Learn, Teach

Ketchup on Rusty

Spring has hit Seattle like a damp blanket. It's better than the 30-days-of-rain from January though, and people are finally getting the moss scraped off their backs. The days are actually light for over 12 hours now, the grass is growing (I've mowed thrice!), and all manner of creatures great and small are crawling and flying.

At the onset of every winter, I say to myself, "This winter I am going to use my gloomy days off and dark week nights to ________," and by this time every year I have done none of it and wonder where the winter went.

One winter a few years ago, I was going to get abs that I could see. That didn't, and still hasn't, happened, although I am in fair shape. Every winter for the past 10 years I've determined that I was going to pass the Microsoft certification exams. I don't even remember why I wanted to do it in the first place, but I've intended to do it for so long now that it is something that just has to get done (I hope that will put it to rest even though MS changes the certification levels every three years).

Two winters ago my wife and I started a business. We did the business plan, created the website, filed the forms, and did some advertising. And you know what? Not even a single call! It was depressing. Since then, we've pretty much shelved the business, but the website is still out there. I have gotten a few calls, and it has actually picked up a bit lately. In fact, I'm working on my second $300 gig - woot - or I would be if I wasn't posting this (actually, I should say retyping this since the first time I posted this my browser crashed and didn't save anything).

At my day job my morale is pretty high. Even though I'm about 5 rungs too low on the corporate ladder to merit an office with a door, I've managed to negotiate my way into one. It's a tiny room between the men's room and the women's locker room in a narrow hallway with no exterior windows. The walls are like a fun house - none are 90 degrees, so the desk doesn't really fit in there. There's also this fan in the ceiling that I worry is the exhaust from the intake over the men's toilettes next door. But it's quiet and no one bothers me!

At work, I've also started a community collaboration site for developers in my region to contribute code, do book reviews, and discuss lessons learned. So far, I'm about the only one contributing anything though. My leadership style subscribes to the idiom of "Lead by example," but so far, that's not working. What have you done to motivate peers?

There's one guy who I asked to participate in the book club, and he agreed. Then later he said he wouldn't do it because he had two young children. I asked him what I could do to make it easier for him, and he told me to come read them to sleep at night :) So, I bought him a copy of Cat in the Hat on VHS and a copy of the book out of my own pocket and he was appreciative and said he'd participate. But, he still hasn't contributed.

That's the news from Lake Washington. Good night, and good luck.

Learning Design Patterns – Iterator Pattern

This week I'll be stepping through the Iterator Pattern in my series on design patterns plucked fromthis book and from examples on the Internet.

What is it?
The Iterator Pattern encapsulates the functionality for stepping through a collection of items. The iterator object implements the stepping; the aggregate itself does not step through its own collection.

The pattern generally has a few of methods like first(), hasNext(), Next(), isDone() in some combination. In some programming languages it is possible to step through an iterator using a For Each item in Aggregate....<code>....Next type of construct.

Where is it used?
Anywhere there is a group of items. An array list is a common example; an iterator would step through the array items until the end of the collection was reached.

But why?
The iterator separates out the functionality of stepping through a group of items into its own class - promoting one-class, one-responsibility design which gives the aggregate only one reason to change itself instead of two. Separating iteration out encapsulates the functionality so that clients can expect predictable results when reviewing a collection, which promotes polymorphism.

OK, and how is it implemented?

//Java

//create a concrete aggregate class
public class BookList {
	//create a collection of books
	Hashtable bookItems = new Hashtable();

	public BookList() {
		//constructor code
	}

	public void addBook(Book book) {
		//add the book to the collection
		bookItems.put(book.getISBN(), book);
	}

	//Return an iterator to step through book list.
	//The booklist uses a hashtable to contain its collection,
	//another object (say customerList) may use an arraylist
	//for its collection.  By creating an generic iterator for both
	//concrete aggregate objects, it promotes polymorphism.
	public Iterator createIterator() {
		//iterate through just the book items
		return bookItmes.values().iterator();
	}
}


//Our booklist uses a hastable, which provides its own iterator method.  
//a more generic collection may need its own iterator created, something
//like this:
public class BookShelfIterator implements Iterator {
	BookShelf[] list;
	int position = 0;

	public BookShelfIterator(BookShelf[] list) {
		this.list = list;
	}

	public Object next() {
		//implementation here
	}

	public boolean hasNext() {
		//implementation here
	}
}


//the iterator interface for BookShelfIterator:
public interface Iterator {
	boolean hasNext();
	Object newt();
}

House of Software Development

We've started a software developer's book club at work, and our first book is Code Complete, 2nd ed. by Steve McConnell - probably the highest recommended book on software development today.

Our division is just starting to organize itself from a staff-augmentation focus where we'd help out clients with relatively quick and easy programming solutions to a structured software development focus. It's more of an attitude shift than a job-type shift, really. We aren't going to start selling shrink-wrap, we're just going to start laying down some procedures and standards and a methodology of sorts.

Coincidentally to reading the first chapter which reviews the major aspects of software development and discusses different analogies (including that of building a house), my boss asked me last week to basically define my own role in the new hierarchy, which itself is still being defined daily.

So, I smartly put together the following diagram based on Steve's ideas, and told my boss that I wanted to be improving techniques and finding tools for the "green level" in the cartoon below, and as my career progressed, I wanted to move into the "blue level". He has a software background from a decade ago (COBOL), and knows essentially what it's all about, but I think he was really impressed with the clarity and completeness of the analogy. Suffice it to say, he forwarded my silly cartoon (which he loved, since he has a good since of humor) to the group including the text that said I was in charge of the "green level" and would later be in charge of the "blue level". Nice :) Now I owe Steve a bottle of champagne, too.

This is the house of software development. Like any building, the house is only as good as its foundation, and as you continue building to the roof, the higher levels are dependent upon the lower. There are other components not shown here since they are outside of our group (like infrastructure, which would be like the plumbing, and sales, which would be like the people living in the house who are trying to sell it).

The different color gradients represent different roles or responsibilities.

  • Purple – Problem definition, and requirements gathering are done by a business analyst. Output includes scope, functional spec.
  • Light Blue – the design and architecture are done by a senior developer by using the documentation of the lower level. Output for this level includes technical spec and may include the database and data logic on medium to large projects. This level sets the tone for the rest of the project (decides if dedicated testers needed, what level of testing needs to be done, what procedures need to be used, number of developers needed)
  • Green – the programmers take the documentation produced by the lower tiers and start constructing the code. Output includes code, GUI, and possibly unit tests depending on small to medium sized projects; larger projects may have dedicated testers.
  • Orange – the overall testing, support, and QA/QC sits on top of the house. The system testing includes pre-release testing, issue tracking, and post-release support. This role has the final say on quality and effectively signs off on the project. When issues come in post-release, this role directs those issues back to the green band for corrective maintenance, but provides the tool for tracking issues.

Learning Design Patterns – Template Method Pattern

This week I'll be examining the Template Method Pattern in my series on design patterns plucked fromthis book and from examples on the Internet.

What is it?
The Template Method Pattern lays out the steps in a process (algorithm) and allows subclasses to handle one or more of the steps internally. The pattern has a method that just contains a list of method calls to complete the process (create something, package it, sort it, deliver) that can not be overriden or augmented. Some of the process methods may be handled by the pattern (create something and deliver), while it makes the subclasses handle the others (sort it, package it).

The pattern also can have "hooks" in it, which are methods that have no implementation, or a default implementation, that the subclasses can choose to override or not.

Where is it used?
The Template Method Pattern is one of the most frequently used patterns around. It especially comes in handy for developing frameworks.

But why?
The Template Method Pattern encapsulates algorithms, and is used wherever a process, or some steps in a process, are being duplicated by classes - the pattern allows the code to be refactored so that the duplication can be eliminated by pulling that code into the pattern.

OK, and how is it implemented?

//Java

abstract class ShipSoftware {

	//declare the template method final so that it cannot be overridden
	final void ship {
		createMedia();
		packageMedia();
		postalSortByZip();
		deliver();
	}

	//make the subclass decide whether to put the software
	//on a CD or DVD or other medium
	abstract void createMedia();

	void packageMedia() {
		system.out.println("Putting software in a box");
	}

	void postalSortByZip() {
		system.out.println("Sorting packages by zip code to decrease shipping rates");
	}

	void deliver() {
		system.out.println("Drop off packages at Post Office");
	}

}


public class ShipMyNewestProduct extends ShipSoftware {

	//implement the creation
	public void createMedia() {
		system.out.println("Burn software on CD");
	}
}

Adopt a mentor

It was only a little more than a year ago that my supervisor sent me a link to Joel's site on software development. Hard to believe how far my career has come since then! I've switched jobs am no longer an under-paid grunt, and I credit a lot of it to Joel's site.

It didn't take me long to adopt Joel as my mentor. His essays on software development, and the crowd of great folks who contribute to the forums, woke me up and got me interested in software development as a craft. I started using his painless software scheduling, and more importantly, started reading the books on his book lists. I started off with the two classics Peopleware and The Mythical Man Month - talk about eye-opening books!

When I started my current job about 9 months ago, I was the only full-time developer in the office of an international consulting company. I was assigned a few small projects at first and was able to use Joel's template for functional specs, and his spreadsheet for schedule tracking. I installed a source control system, and started trying to improve the system from within to bring our division's score up on the Joel test. I was doing things the grunt way - doing what I could with the power I had to use the tools I wanted on the projects I was working on.

Management took notice of the good job I was doing. People were raving about my interview questions and how I actually made applicants write code in the interview. When the division organized itself from flat and ambiguous, to structured into stove pipes like sales, app development, etc., I was able to use it as an excuse to pull every developer in the region (about 5 offices, 10 developers) into a community of application developers. I created a Groove workspace for us all to collaborate and share code snips, talk about standards and patterns and practices, and jell as a team. For the first time we'll be working on projects together even though we're in different offices, and jelling as a team will be very important.

At my annual review I was surprised with a large raise, and just a week ago I received a call from my boss twice-removed (two tiers up). He called to say what a great job I was doing and how he expected everyone in the office to be working for me one day (ha!), then he gave me a big bonus! It was incredible - no one at my level gets bonuses at our company; they are reserved for the elders who are paid too much to give big raises to.

So, I just want to take this opportunity to publicly thank Joel for being such a great mentor. It takes a lot of effort and a lot of guts to put all of his opinions out on his site, and I think he provides a great service. All said, since I've adopted him as my mentor just over a year ago, my salary has increased by 50% and my career has really taken off. I should really send him a bottle of champagne! I'll have to ask him what he likes.

Learning Design Patterns – Facade Pattern

This week I'll be simplifying my life with the Facade Pattern in my series on design patterns plucked from this book and from examples on the Internet.

What is it?
The Facade Pattern simplifies a complex interface so that it's client can rely on simple methods in the facade that handle multi-step calls to subclasses. The client might call facade.PowerUp, then the facade would turn on all of the subcomponents in the correct order and adjust their initial properties.

Where is it used?
The Facade Pattern is used to simplify processes that rely on multiple objects to complete, and to simplify frameworks (or even individual classes) that have an overwhelming number of interface methods.

The pattern is also used to adhere to the Principle of Least Knowledge, an OO design principle also known as the Law of Demeter. The principle recommends that a class should not talk to anyone except its close friends, who are:

  • Itself
  • Someone passed in as a parameter
  • Anyone who it instantiates
  • Anyone who is in it's instance variable list

In other words, don't instantiate an object (new Friend), return another object (Friend.Friend), and call the second friend's method (Friend.Friend.ComePlay).

But why?
Besides simplifying a complex interface and promoting good design through the Principle of Least Knowledge, the pattern also helps the design of an application by decoupling the client from all of the subclasses - if a subclass method changes, then the update is made in the facade without affecting the client code.

OK, and how is it implemented?

//Java


public class SecurityLockFacade {
	//indicates pass or fail
	VerificationLight light;
	VerificationBeeper beeper;
	Door door;
	
	public SecurityLock (Door door){
		//initialize light, etc.
		this.door = door;
	}

	public boolean open(Badge badge) {
		boolean authorized = door.authorized(badge);

		if (authorized) {
			light.green();
			door.open();
			return true;
		} else {
			light.red();
			beeper.beep();
			return false;
		}
	}
			
}

// Create a client that doesn't need to know about all 
// the beeping and lights, just calls open
public class TestDoor {

	public static void main(Door door, Badge badge) {
		SecurityLockFacade securityLock = 
		  new SecurityLockFacade(door);

		if (securityLock.open(badge)) {
			//walk in
		} else	{
			//FBI has been alerted; run away!
		};
	}
}

Learning Design Patterns – Adapter Pattern

This week I'll be switching over to the Adapter Pattern in my series on design patterns plucked fromthis book and from examples on the Internet.

What is it?
I remember when I was about 6 I was helping Dad replace a section of board-fence with chain-link fencing (by helping, I mean I was standing there picking my nose and asking him inane questions). He had taken the old fence out, which left three round holes in the ground where the fence posts were. Maybe to quiet me, or maybe just because he enjoys being ornery, he asked if I could explain how those square fence posts had fit into the round holes we were staring at. That question stumped me for years (I blame that on all the lead buckshot I ingested from the pheasants Dad hunted), but now I see that the Adapter Pattern is the answer (or not, but it makes a good story, right!?)

The Adapter Pattern converts one interface into another so that two classes can work together without having to change their code. The most common analogy would be any electronic adapter you can think of; one that converts a US plug to a European plug (you could combine this with the Decorator Pattern to add status lights and other features), or a big headphone jack to a small headphone jack.

There are actually two flavors of the pattern, the Object Adapter, which I'll cover today, and the Class Adapter, which I'll leave to your investigation in the interest of brevity. Suffice it to say, the class Adapter uses multiple inheritance (not possible in Java) and subclasses to adapt, while the Object Adapter uses composition to pass the requests through.

Where is it used?
The Adapter Pattern can be used to connect old code to new code. Maybe you have an existing code base that has a set interface for something, and you buy a 3rd party tool that you'd like to plug into, but that uses a different interface. Instead of rewriting your old code to match the new tool, you could write an adapter to sit between the two.

But why?
Why not just rewrite one of the interfaces and the code that is associated with it so that no adapter is needed? You would have to weigh the risk in opening up new code which can lead to unexpected consequences (bugs) against writing an adapter and handling all the interface handshakes.

Maybe you have some newer code that is programmed to a new interface, and some older code that uses the old interface, what would you do then? You could create a two-way adapter that supports both interfaces.

OK, and how is it implemented?

//Java


//We have an old outlet that only accepts two-pronged plugs
public interface UngroundedOutlet {
	public void TwoProngPlugin();
	public void TwoProngUnplug();
}


//And our new plug has three prongs
public class GroundedPlug {
	public void ThreeProngPlugin();
	public void ThreeProngUnplug();
}

//so we develop an adapter to allow the grounded plug to plugin to the
//ungrounded outlet
public class GroundedAdapter implements UngroundedOutlet {
	GroundedPlug plug;

	public GroundedAdapter(GroundedPlug plug) {
		this.plug = plug;
	}

	public void TwoProngPlugIn() {
		plug.ThreeProngPlugin();
	}


	public void TwoProngUnplug() {
		plug.ThreeProngUnplug();
	}
}

//Now to test it:
public class testPlug {
	public static void main(String[] args) {
		//create the three-prong plug
		Plug groundedPlug = new GroundedPlug();
		//create the adapter
		UngroundedOutlet adapter = new GroundedAdapter(groundedPlug);
		//plug in the adapter to the outlet
		adapter.TwoProngPlugIn();

	}
}

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();
	}
}