One-bytes #3: Methods returning multiple values or the Tuples

*** #3.1 How to return multiple values from method***
Quick one today – how to write a method that returns more than one value. There are two ways: i) use out keyword, ii) use generic class Tuple. In the first approach we return first value as we usually do, the second value will be passed as parameter with out keyword. Take a look at example method:

Now if we want to make use of this method we either need to have a variable pre-declared and pass it into the method or declare it inline in the place of invocation:

Nice and simple, right? It the second approach we make use of Tuple generic class. It works with up to 8 generic parameters meaning that we can return 8 values (but nobody says that one of the returned values is another tuple, so in practice we can go for how many values as we want). Here’s an example:

So this method in fact returns one value of type Tuple. So how to access the values we really want?

Again, nice and simple. Which way is better? I guess the one you prefer 🙂

Tuple Class on

One-bytes #2: Selection in WPF, OnPropertyChanged parameters

*** #2.1 Item selection in WPF selector-enabled items control***
In WPF we can use multiple types of controls to display collections of items which allow user to select one or multiple items from the collection. In this post I’m going to discuss what single selection possibilities they offer.
Let’s start with inheritance hierarchy – controls that allow such selection inherit from System.Windows.Controls.Primitives.Selector. If we take a look at what properties they have we find four that may be involved in selection process:

  •  SelectedIndex – Gets or sets the index of the first item in the current selection or returns negative one (-1) if the selection is empty.
  • SelectedItem – Gets or sets the first item in the current selection or returns null if the selection is empty
  • SelectedValue – Gets or sets the value of the SelectedItem, obtained by using SelectedValuePath.
  • SelectedValuePath – Gets or sets the path that is used to get the SelectedValue from the SelectedItem.

So, there are three ways get the selected item: i) its integer index in the collection, ii) the item itself, iii) one desired value from the item. 
I have prepared a quick demo to show that. The app displays a ListBox of custom class objects and once an item is selected displays all three ways to present the selection. Let’s take a look into the code, starting with the class of objects that our list will contain:

The list will be generated and stored in view model. The view model will also have three public properties: i) ItemSelectedIndex of type integer bound to SelectedIndex property of  our ListBox, ii) ItemSelectedItem of type Item bound to SelectedItem, iii) ItemSelectedValue of type string bound to SelectedValue. Let’s take a look at complete ViewModel class:

And now the most important part – the view. As mentioned above as a container for collection we will use ListBox and bound properties as it was described when discussing the view model class. The only thing that’s left is setting correct value to SelectedValuePath property. In this case we want to use Name property of our item class so we need to set SelectedValuePath to “Name”. Here’s how to set the ListBox up:

Now, to use the selected index, item or value which are bound to corresponding properties in view model we need to add some controls and again bound them to view model properties:

And that’s it. To sum things up – there are three ways to access selected item in a selector control in WPF: by its index, by the item itself or by one particular value in the item.

*** #2.2 Passing property name to OnPropertyChanged()***
Second thing I want to mention today is a hint how to make invoking OnPropertyChanged() method in a property setter a bit more controlled when not using any MVVM framework.
ViewModels usually implement INotifyPropertyChanged interface which purpose is to notify views when a property has been updated. This is done by invoking OnPropertyChanged method with property name passed as a parameter.

That is not the best way. What if we decide to change the property name and the backing field can also be changed somewhere else? In this case we need to go and manually change the hard-coded property name. So what can be done instead is this:

Having passed the parameter this way we can simply go to the property, right click and rename it using Visual Studio renaming tool which will update all calls to this property. Definitely better!

Design Patterns #10: State

Design patterns episode 10 – State

Happy Christmas!! Isn’t it a good time to write a post?
Let me start with an apology. In previous post about patterns (composite) I promised to keep that one week/one pattern schedule but as you can see I have failed. But in the meantime I posted something different (one-bytes #1) so I feel forgiven to some extent. Learnt by experience I promise nothing this time. With that being said we can proceed to the next pattern.

Today’s hero is the State. We all know those simple machines which operation model is frequently very simple but closed within exact patterns. For instance the example given in Head First book – a vending machine. It allows only two or three possible interactions (insert coin, get coin back or get the product) and serves one particular purpose (sell products). Its operation model is base on states: the machine can have a coin inserted, can be out of products, etc. So the machine changes its internal state and this change implicates change of behaviour.

Let’s take a look at the definition and the diagram.

The State Pattern allows an object to alter its behavior when its internal state changes. The object will appear to change its class.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004) 

In object-oriented programming the above definition is realised by representing these internal states by different implementations of one interface (or inherited from an abstract class). The important thing is the fact the state changes internally. It is not possible to set state from outside. If we go back and think about strategy pattern we will probably see that these two pattern are similar but that closure to changes from outside is what makes them different.

This the diagram depicting the state pattern and similarly to strategy pattern we have encapsulation of behaviour in a separate class: behaviour of Operation() method in context class is encapsulated in state object. It is possible to have multiple states but transitions between them must be done privately. User of state context must not be able to enforce the context to switch state in any other means than normal operation on the context, intended by designer. We don’t have any public method to set the current state from outside. And that is the key to state pattern.

I have used a prepaid electricity meter to show the pattern. It can be thought of as a state machine: it can be switch off, switched on but idle, conducting electricity to appliances or be out of credits. Let’s start with the meter interface:

It exposes two properties: one is the credit that the meter is topped-up with, the other is current state of the meter. Both of them are get-only: there is specific method to top-up and the state cannot be set from the outside. Other than that we have methods to turn the meter on/off, start delivering power (for specified number of cycles)  and already mentioned TopUp() method.

The implementation of the meter is slightly more complicated. First we need to equip properties from the interface with setters. Next we need properties for each of the possible states. In this case there are three states: OnStateOffState and MinusState. Other than that we have methods to manipulate with credit and a constructor. This is important: we initialise state instances, set credit to zero and set current state to OffState. The last step is four methods from the IMeter interface. These methods don’t have their own implementation but they call current state object to execute its corresponding operations.
Now the abstraction of state class. In this case I’m using abstract class because I need some not public members, force the inheriting classes to set reference in constructor to the meter the state is going to be used with, and reuse some common pieces of code.

As you can see states will have all the methods that the meter will call in different states. The TopUp() methods has default implementation because it will the same for OnState and MinusState, method ReachZero will be called whenever the meter runs out of credit. It doesn’t need to be virtual because no override will ever be needed.
The last pieces of code would be actual implementations of the sates. Let’s take a look at just one:

As you can see each state provide its own implementation of actions possible for the meter (except for TopUp() which as stated earlier can be shared and in this case it is, but it isn’t in OffState where it is overridden to simply write out on console that the meter is off). Note that some of them changes the state – that’s the core of this pattern: the internal change of state.
Having all the states implemented we can see how it works:

The above would generate output like this:
As you can see we invoked Start() method on one and the same object and we got three different results which all depended on the state in which the object had been, and some of which changed the state of the object. That’s the way how the state pattern works.

Before I prepared this example I had prepared another: a model of vending machine. It is a WPF app. The reason I decided to go for something different was the fact that it had become a bit unclear in the code. Simple console app is much better to illustrate the  pattern. However I did not abandoned the code and you can take a look at this as well. Here’s quick video how it works and the source code you will find at the bottom of this post.

So that’s it for today. Hope you like it 🙂 Before you go please find some useful links below. Enjoy!

Source code – IMeter: TXT file
Source code – Vending machine: GitHub

One-bytes #1: Menu item commands, boxing vs. ToString()

Hello there!
With this post I’m starting new category: one-bytes. These posts will be compiled of two or three shorter forms abut things that don’t qualify for so to say full-size post. Name of the category refers to snack meals, so called one-bite foods: one bite => one byte. Quick to prepare, good to get your taste-buds tingling.  Enjoy!

*** #1.1 Binding a command to MenuItem in ContextMenu ***
It happend one time that I had been struggling with binding a command to a MenuItem in ContextMenu. The code was more or less like this:

It turned out that since ContextMenu is not present in WPF visual tree it was not possible to bind the command as it’s usually done. The solution was to use BindingProxy class that inherits from Freezable.

Having this class we can create its instance as a resource (in my case it was an user control) and set the Data property to {Binding}:

This will bound the Data property to whatever is set as DataContext in the user control itself. Now, through the BindingProxy instance we can access that DataContext outside the visual tree:

This solution was proposed by Thomas Levesque.
Blog post by Thomas Levesque
Question on StackOverflow

*** #1.2 String.Format() vs. boxing ***
There is a thing using String.Format() method with value types (such as integers). That thing is the fact that this method takes objects as args and if a value type given as parameter it will be boxed. Boxing is a process when a value type is converted to an object. That involves moving the value from stack to heap and replacing it on a stack with a reference to heap address where the actual value is stored. (More on boxing/unboxing can be found here: [link]).
So, what can be done to avoid that – simply pass arguments with ToString() method invoked. This will save a bit on performance – that’s the theory. So I tested it. I take an array of one million integers and another array with the same amount of doubles and pass them into String.Format() method. And the theory is confirmed – avoiding boxing by invoking ToString() method makes it faster.

To make the results reliable I arranged everything as unit tests run one after another (not parallel) and the actual tests were preceded by a test that did nothing – that is to make sure that the filling arrays in test class constructor does not distort actual test running time. So the results are that the process without boxing is faster by 3,7% for doubles and 4,9% for integers. Please, keep in mind that the test sample was one million values.
Does it mean that it’s no point in invoking ToString()? My opinion is that in this case boxing operation is redundant and not necessary so it should be avoided.

Design Patterns #9: Composite

Design patterns episode 9 – Composite

With unexpected delay but patterns are back! In this episode – composite.

The composite is generally used to model tree-like structures in a way that classes that are using the composite can handle its elements in one particular way without having to distinguish whether an element has children – a composite, or hasn’t – a leaf (in other words, whether we can go further down the tree or element is a dead-end).

The first thing that comes up when thinking about that kind of structure would be a directory tree where folders are composites and files are leafs. Or any other structure alike: corporate structure (managers and subordinates), online shops (categories and concrete items) and many many more.

Let’s see how the Head First book defines this pattern:

The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite lets client treat individual objects and composition of objects uniformly.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004) 

So, in other words we have tree structure of objects and collection of objects and the client doesn’t need to care about if it’s a leaf or a composite. This is the key feature of this pattern. For instance, let’s think about file system where we have files and directories. Both of them are elements of file system and should be treated the same: the client can perform the same operations on both – rename, delete, get size etc. But obviously we can do more things with directories (as this is a collection of files and directories), therefore composite pattern isn’t applicable here (of course you could use typecasting to make it work but that’s a different thing).
The diagram shows what discussed above – both concretions are treated the same, nothing different can client do with one or the other type. The diagram presented here is different than what’s in the book. The book adds further methods: add()remove(),  getChild(). But isn’t that inconsistent with the definition? How can you add a further child to a leaf? You could throw an exception but wouldn’t that violate the Interface Segregation Principle? That kind of issues have been greatly discussed here by the guy who I quoted on multiple occasions.
So, to conclude this aspect of the pattern – my opinion is that we should stick to ISP and not force any class to implement something that the class doesn’t use. Period. Let’s move on to code example.


In our code example we’re going to build a store’s menu. Let’s start with the abstraction:

Our IStoreElement consist of name property and a method to list self in the menu: there will be different implementations of this method for leaves and composites. This method can take optional argument as we want to nicely format the menu by indentation of sub-components.
Now the leaf class:

Leaf’s implementation of ListOut() method works that it returns a string with given number of dashes and its name.
And finally composite class:

This class is equipped with private list of objects that implement our base interface. This list can be set in constructor.
The ListOut() method starts with the same thing that counterparting method in leaves but before returning the value recursively invokes the same method for all IStoreElements that the composite holds in its private list. This invocation takes indent parameter increased by 1. This way we achieve that nice formatting of the list once requested in the topmost component.
Now, let’s see how it work all together:

We generate the list and then print to the console the string returned by ListOut().

To sum things up: he Composite Pattern is used to represent tree-like structures where all their elements can be treated uniformly, where single components are called leaves and collections of components are called composites. The pattern can be equipped with methods to modify the content but this lead to violation of Interface Segregation Principle.

Next week: the State Pattern. I hope that this time without any delay. Check the links and source code below. Thank you!

Composite pattern by Christopher Okhravi: link [YouTube]
Composite vs. Decorator by Christopher Okhravi: link [YouTube]
Composite pattern by Michael: link [YouTube]
Source code: TXT file

Design Patterns #8: Iterator

Design patterns episode 8 – Iterator

Today’s pattern is the Iterator – an easy way to cycle through collections without worrying how it is achieved – in simple words. Let’s see what the Head First book has to say about that.


The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying implementation.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004)

This is achieved by two interfaces: one abstracts the iterator, the other abstracts the aggregator. To make things clear – the aggregator is a class that provides a collection we want to iterate through.

So, there is a class called ConcreteAggregator that has a collection of objects. The diagram above depicts a generic version of the pattern (this not a must, you can write your own specific iterator) so the collection stores objects of type T. The ConcreteAggregator doesn’t want to allow direct access to that collection so it implements the IAggregator interface to allow the client to use the iterator by invoking GetIterator() method which returns ConcreteIterator which in turn implements the IIterator interface. This interface is the core of the pattern: it provides methods to actually iterate through the collection: i) Reset() to move index pointer to the start of the collection, ii) HasNext() to indicate whether there are more elements in the collection, and finally iii) Next() to get an element from the collection.


The .NET Framework uses this pattern widely in collections. To make long story short – in System.Collections (or System.Collections.Generic) namespace you can find IEnumerable interface which has only one method: GetEnumerator() – sounds familiar, right? Most of the collections implement this interface – Lists or dictionaries for instance, not to look far. This method returns an object the implement IEnumerator interface. In this case this interface is slightly different:

This post .NET namespaces Explanation
void Reset()
void Reset()
no difference
bool HasNext()
bool MoveNext()
In .NET interface this method moves the pointer to next element and returns: true – if advanced successfully without passing the end, false – if passed the last element and set the pointer to the first element
<T> Next()
object or <T> Current { get; }
In .NET this property returns object at current position of the pointer without moving to next element


In the example we will create a book library. This class will store books in a private list but will expose an iterator. Let’s start with the interfaces:

They’ve been already discussed above so the only thing I would like you to pay attention to is the fact that they’re generic.
Next step – implement the iterator:

To complicate the code a bit the implementation will use an array to store the values, beside that we also have an integer to indicate current position. In the constructor we initialise the array of values and copy them from the list passed as an argument. The last thing we need to do in the constructor is to set the index indicator to Reset() the position indicator. The only thing that Reset() method do is to set value of position indicator to -1. Why -1 not 0? That is because we use Next() method to get values: this method first increments the indicator and then extracts the value. Method HasNext() simply check if position index increment operation would not exceed the length of the array of values.

The Library class is very simple – in its constructor we fill the list of books and implement the IAggregator interface: the GetIterator() method returns new LibraryIterator with list of books passed as an argument.
And everything works perfectly. Here’s some code to test that:

And that’s it – the iterator in its full swing:
Here’s couple of links that may also be useful:
Why iterator is important: [YouTube] by Christopher Okhravi
Another code example: [YouTube] by Michael

Source code: [TXT file]

Design Patterns #7: Template Method

Design patterns episode 7 – Template Method

This post is about template method pattern. Those who are familiar with the Head First book may be wondering where’s facade. The answer to that question is that I deliberately decided to skip the facade at this point. I will definitely come back to this, but maybe next time. Now, let’s move on to the template method.


The Template Method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004) 

What the above mean? It means that the pattern is built on base abstract class which has a public method which defines our algorithm by invoking in intended order some other methods which may be overridden by subclasses. The algorithm’s member methods may provide default implementation of be abstract forcing the subclasses to provide their own unique implementation.

Most of the examples you can find is based on preparation of pizza, coffee etc. And they’re really good. Pizza for instance: when you’re cooking a pizza no matter what style you basically do the same: prepare dough, add sauce, toppings, put it into oven and cut. That’s the algorithm. But you certainly do different dough for American pizza and for traditional Italian pizza, you add different toppings for vegetarian pizza and for meat pizza – and that’s the where we may want to override our sub-methods of the algorithm.

The code below will not be about pizzas, it’s going to be a generic code that does nothing but show how the pattern may be implemented.
Let’s take a look at our base class:

As you can see our TemplateMethod() is not marked as virtual therefore it cannot be overridden – this is the skeleton of the algorithm. In its body this method invoke all member methods – subOperations from 0 to 3. Interesting thing is that the last member method will be executed only if a condition is true. This is called a hook. This is one way to alter the invocation list of the algorithm. You don’t need to use is but it’s good to know. Besides that we have combination of  methods with default implementation, abstract methods and those you cannot overwrite. In our case only one methods needs to be implemented in a subclass – let’s take look:

So, our concrete implementation overwrites one method with implementation in  base class and provides implementation of one abstract class. Simple, so let’s see how it works:

To witness the template method we instantiate new ConcreteTemplate and observe how it behaves – with optional method executed and without.

And that’s the template method pattern. The best explanation of this pattern I’ve found so far is in the Head First book but below you will find also one link to a YouTube video with Phil Japikse – you may find it useful.
Thanks for today and expect the next pattern next week.

Design Patterns: Template Method – YouTube
Source code: TXT file

Design Patterns #6: Adapter

Continuing with design patterns. Time for Adapter. This pattern is a structural pattern whose purpose is to convert interface (in a meaning of public members of the class, not necessarily interface as a programming language feature) so the class is usable with client’s code. The Head First book defines this pattern as:

The Adapter Pattern converts the interface of a class into another interface the client expects. Adapter lets classes work that couldn’t otherwise because of incompatible interfaces.
(Freeman, Eric, et al. Head First Design Patterns. O’Reilly Media, Inc. 2004)

Generally, it may be said that the adapter pattern wraps an object that cannot be used by a client and exposes an interface that allow the client to use that object. Let’s take a look at the diagram:

So, we have a client that wants to use an object that implements IExpected interface, however we already have a class that does what we need but doesn’t have a compatible interface (unsupported class). So, to solve the problem we need an adapter. The adapter will have all public members that the client expects – will implement the IExpected interface and at the same time will privately wrap an instance of unsupported class (passed in a constructor, for instance). Once the client calls the adapter, the adapter will in turn call the wrapped unsupported class and return results to the client (and if required convert them to what the client expects). And that’s it, simple as that.

Let’s take a look at code example now. We have a class that calculates area and perimeter of a rectangle. (These calculations are very simple but to give the example a little bit more depth think of them as of very sophisticated and complicated). That class operates on double type. Our client, however wants to calculate area and perimeter of squares only and operates on integers. We could i) write a new class to handle that but we don’t want to do that because we already have a class that is capable to perform such calculations (square is a rectangle after all, right?); ii) modify our client to work with the existing class, but again we don’t want to break anything elsewhere (OCP right?). That’s why the right solution here is the adapter.
Let’s compare what we have and what we need:

So, the differences are: i) types (already mentioned int vs. double), ii) method names, iii) number or arguments required for counterparting methods.
Now the adapter. First of all it needs to wrap the already existing class and set its instance by passing it through constructor; then we need to implement methods required by IExpected interface in a way that they call the wrapped object and return values converted to integers.

Let’s write a quick test:

Everything works perfectly.

Object adapter vs. Class adapter
The explanation and code example is an object adapter. This means that the adapter works with a concrete instance of adapted object. Advantage of this solution is that this type of adapter will work also with objects of classes which are derived from adapted superclass.
There is also another adapter-type pattern called class adapter. In this type you don’t need an instance of adapted class, instead the adapter class inherits from both: expected class (or interface) and adapted class. Remember that inheriting from more than one superclass is not possible, what could be done is to create new class that inherits from a class that needs to be adapted and implements expected interface. This approach may also be useful but keep in mind that it looses the advantage of composition over inheritance.

To sum things up: adapters are extremely useful everywhere there is a need to use something that can do what we need but doesn’t have compatible interface.
Plan for next week: Facade

Don’t forget to check the links below!

Christopher Okhravi about Adapter Pattern: [YouTube]
Source code: [TXT file]

Design Patterns #5: Command

delayed but here I am with the next design pattern. This time it’s the command pattern. Those who are familiar with the Head First book might be wondering where’s singleton. The Some time ago I wrote a post about singleton (which you can find [here]), so there’s no point in going back. Therefore we go straight to the command.

The command pattern encapsulate calls to objects and provides undo mechanism for those calls. This is achieved by command classes which can perform an action over an object and are assigned to callers. Let’s take a look at the diagram:

Let’s start discussing the above from the ICommand interface and its concrete implementation. The interface has two methods: one for proper action, one for undoing the action. The implementation additionally has reference to IReciever object which defines over what type the command can execute. This is not mandatory, for instance you can declare your execute() and undo() methods to take IReciever as parameter. The important thing is that concrete command operates on certain type, however the caller doesn’t know anything about the receiver, the only responsibility of the caller is (so to speak) to call.

The example in the book is really great. The authors presented a programmable remote controller for an intelligent house. The controller has multiple buttons which can be assigned with a command that can operate lights, home cinema etc.

Our example will be programmable counter. The counter will have 5 buttons to manipulate the value of the counter. The counter will have undo feature. This time the code example will have WinForms GUI with custom controls for buttons-callers and counter-receiver.

The caller will have a button to execute a command and a drop-down list to ‘program’ the button with one of the available commands.

 The receiver will have a text-box with current value, button to reset the counter, button to undo last command and a list of all executed commands (operating in FIFO-like mode, the newest on top, the newest first to undo). This user-control will also implement IReceiver interface which provides integer property CounterValue (which play the role of action() method from the diagram) on which the commands will operate and AddToTrace methods which will be used by a command to enroll itself to a command trace for undoing.

Now, the command. Let’s start with the interface:

Beside two already discussed methods Execute() and Undo() the interface provides also Name property (which will be used by the UI) and Receiver property for referencing the counter on which the command will operate.

Concrete command
Now, let’s take a look at one of the commands which implements ICommand interface:

The Execute() method increments the value of the counter and puts the command to the top of the command trace for undoing. The Undo() method simply does the opposite of the Execute() method which is to decrease the counter by one. Removing it from the command trace will be the responsibility of the undo button in the counter user-control.

Command trace
To make it possible we need to keep track of what commands have been executed. For that reason our counter user-control is equipped with a private list that holds objects of type ICommand. The command can enrol itself to the list by invoking AddToTrace method of the receiver and pass itself as an argument.

Once we have the list we can use the undo button which takes the first element off the command trace and invokes the Undo() method.

And that’s it. Take a look how this operates. 

So, that’s it for today. Don’t forget about the source code below and come back next week!

Source code: ZIP file

Design Patterns #4: Factories

Hello there!
It already is a weekend so time for next pattern from the list: factories. Factories are creational-type patterns which means they are used to (surprise, surprise) to create instances. There are three types of factories (of which only latter two are considered as design patterns): simple factory, factory method and abstract factory. Let’s start with the non-pattern one.

Simple factory is a class that has a method to create a certain types of objects where the decision what exactly type to create is made by the factory itself based on given parameters. Assume that we’re building a book store and we want to sell paperbooks, audiobooks and ebooks. We have definitions of a sub-class for each of them implementing IBook base interface. We can build our simple factory in a way that we pass a char parameter and if it matches with first letter of our sub type we create that sub-type:

And that’s it: we have our simple factory. But the problem is that when we want to introduce another sub-type it is necessary to modify that class. And we don’t want that. And why you find [here].

About factory method I’ve already written [one post]. Consider this post as a supplement to the previous one.
Factory method solves the issue we had with simple factory by removing it’s responsibility to decide (based on the parameter) what type exactly to create. If we want to modify the factory we’ve created above we would need to create separate classes responsible for creating each type of book. And that’s what was done in my [first post] about this pattern:

Now, if we need another sub-type we simply create another class that will create new sub-type.
Let’s take a look at the definition:

Factory method pattern defines an interface enabling to create a single object making the sub-class implementing this interface to decide what exactly type of object to create.

What does the above mean? It means that the client at the point of invocation of factory method doesn’t care (and doesn’t need to care) what type is going to be created: the client wants an object and is going to get one. Very good example is provided by Christopher Okhravi [here] – a simulator a national park where multiple types of animals dwell and the simulator care only about the right number of animals, when it needs an animal to spawn it just calls the factory and the factory decides what animal to create. (I’ve already said that multiple times but I highly recommend his [playlist] about design patterns.)
And now the UML:

We have an abstraction of factory method class and its concretion that creates an instance of a class which is a concretion of one interface common to all sub-types of product.

If you know how the factory method works understanding the abstract factory will be a piece of cake. Let’s start with the definition:

Abstract Factory provides an interface for creating multiple related or dependent objects without necessity to define their concrete classes.

And the UML:

So, the client uses a factory to create instances. The factory is abstracted by the interface which has multiple (in the case above two) concretions which create two related sub-types of ProductA and ProductB. The IFactory interface doesn’t specify what concrete classes will be instantiated and the client doesn’t care. It is the concretion of the factory which specifies what sub-types of products exactly to create. So, in really really short we may say that the difference between factory method and abstract factory is that the former creates only one type objects while the latter can create multiple types of objects (related and/or dependent).

And that’s it. Before I say goodbye: have a look at the links below to find out more about factories; plan for next week – singleton.

Christopher Okhravi: Factory Method Pattern – Design Patterns (ep 4)
Christopher Okhravi: Abstract Factory Pattern – Design Patterns (ep 5)
CODE Project: Factory Patterns [Snesh Prajapati]