March 23, 2010 Design Patterns 4 comments
March 23, 2010 Design Patterns 4 comments
I have a story about the doctor who had a very good and fast Mercedes. On the way to work he is often stuck in traffic congestion and this makes him mad and late making his patients suffer. He has a dream of his car becoming Ambulance so that all cars make the way. Only one issue with this: Ambulance should beep loud. Currently his car has no such loud horn. The doctor also doesn’t want to waive his warranty by changing internals of this car. Let’s decorate Mersedes so when you drive it beeps real loud. How can we accomplish this using a Decorator design pattern?
So here we have Car class and Mersedes implementations:
The Decorator pattern is used to add some functionality to your objects. In our example we want to add beeping to the concrete implementation of Car, but also we can add other functionality. So in order to save contract of Car class and have base class for all features we create the CarDecorator class like below:
as you see it has decoratedCar wrapped, that is why patterns is also called Wrapper.
So in order to add some additional functionality we derive from Decorator class:
so it was slight extension – beeping :)
And usage looks very friendly – we cover Mersedes with Ambulance features, after that we can cover it with more abilities, in other words we can add features dynamically.
Output:
I think you extected it. Now lets take a look at the UML diagram of this wisdom:
This pattern has some similarities to the Composite and Adapter patterns. Adapter could change the interface of behavior, but Decorator not (we are derived from Car). Composite works with lot of components, not like Decorator with only one.
February 13, 2010 Design Patterns 2 comments
Imagine that you are game developer. Your game is war stategy. Army has complicated structure: it consists with Hero and three Groups. When King gives decree to treat all soldiers (Hero is also soldier) you want to iterate through all soldiers and call treat() method on each soldier instance. How can this be accomplished easily and without diving into Army structure?
Iterator is the pattern which provides you a way to access all elements in any collection of data without exposing collection implementation.
So in application to our problem. You just don’t want to care about structure of your army – you want some SoldiersIterator to loop through all soldiers in it. Red line is the Iterator (in my mind representation).
Usage
Code below shows usage of iterator. We can loop through all soldiers and increase their health level without thinking of the structure of Army. This should be easy and it is main purpose of Iterator.
Army structure
Army structure has one Hero and could have many Groups which of them could have many Soldiers. So as we see structure of Army is complicated and tree-based. Code below represents instantiating of Army:
Hero is class derived from Soldier and has only one difference – higher health level:
public class Hero extends Soldier {
protected int maxHealthPoints = 500;
public Hero(String name) {
super(name);
}
}
SoldiersIterator
So if we can move through the complicated collection of Soldiers where is that complicity?
Well, it is encapsulated in concrete Iterator class.
private Army _army;
boolean heroIsIterated;
int currentGroup;
int currentGroupSoldier;
public SoldiersIterator(Army army) {
_army = army;
heroIsIterated = false;
currentGroup = 0;
currentGroupSoldier = 0;
}
public boolean hasNext() {
if(!heroIsIterated) return true;
if(currentGroup < _army.ArmyGroups.size())return true;
if(currentGroup == _army.ArmyGroups.size()–1)
if(currentGroupSoldier < _army.ArmyGroups.get(currentGroup).Soldiers.size())return true;
return false;
}
public Soldier next() {
Soldier nextSoldier;
// we still not iterated all soldiers in current group
if (currentGroup < _army.ArmyGroups.size()) {
if (currentGroupSoldier < _army.ArmyGroups.get(currentGroup).Soldiers.size()) {
nextSoldier = _army.ArmyGroups.get(currentGroup).Soldiers.get(currentGroupSoldier);
currentGroupSoldier++;
}
// moving to next group
else {
currentGroup++;
currentGroupSoldier = 0;
return next();
}
}
// hero is the last who left the battlefield
else if (!heroIsIterated) {
heroIsIterated = true;
return _army.ArmyHero;
} else {
// THROW EXCEPTION HERE
throw new IllegalStateException(“End of colletion”);
//or set all counters to 0 and start again, but not recommended
}
return nextSoldier;
}
}
Why my example is not standart and classic?
Because my goal in this article was to higlight the main issue that Iterator solves in such manner that it could be easily understandable. And second reason is that you can read tonns of standard explanations of this Design Pattern.
Main difference between my explanation and others is that classic explanation is more abstrated, it contains abstract Iterator which represents interface for concrete ones, and abstract Aggregate, which creates Iterators needed.
The way I created Iterator looked like
But generally this logic could be hidden under some Aggregate’s method (like GetEnumerator in .NET). For example I could have this:
In .NET world we have IEnumerable<T> and IEnumerator<T> interfaces which provides a lot of help in impementing this pattern:
In Java we have java.lang.Iterable instead of IEnumerable, which is more intuitive naming. I think that Microsoft just wanted to be original in this :).
January 29, 2010 Design Patterns, Java No comments
Imagine that you have shop where your Customers could buy Laptops with configuration they prefer. You need to develop system which will allow you easily build any configuration of Laptop for any User.
How could you easily accomplish this?
Builder is Creational Design Patter which allows you build some whole Product (Laptop) by constructing together some parts like Processor, Memory, Monitor, HDD, Battery and so on.
So your employee talks to Customer and asks questions which memory do you want and so on. Or otherwise if Customer is not technic, employee could ask “Do you need this laptop for gaming?”.
So you need some steps to construct you computer and they are defined in Abstract Builder.
public Laptop getMyLaptop(){
return laptop;
}
//mentioned steps to build laptop
public abstract void setMonitorResolution();
public abstract void setProcessor();
public abstract void setMemory();
public abstract void setHDD();
public abstract void setBattery();
}
If your Customer answers like “Yes, I wanna play… play…!!!“. You already have implementation of Concrete Builder for gaming laptop like:
Or if you Customer is business guy and he watches presentations and exel reports in plain:
To manage steps to build your Laptop basing on the answer you need Director:
Here we have usage code.
BuyLaptop shopForYou = new BuyLaptop();//director
shopForYou.setLaptopBuilder(gamingBuilder);//Customer answered that he wants to play
shopForYou.constructLaptop();
Laptop laptop = shopForYou.getLaptop();//just get what he wants
laptop.print();
Output:
Easy, simple and great pattern.
What have I learned regarding of Java?
Nothing special, just how to format strings:
January 25, 2010 Design Patterns 3 comments
Generally saying Specification is a predicate that determines if an object does or does not satisfy some criteria. By using Specifications you could easily recombine business logic together using boolean logic.
Have you ever thought that bool TryParse(string s, out int result) could be seen as some pattern? Yes we could talk about this method like about specification of integer represented in string, and this is validation usage. This pattern also could be used not only for Validation, but also for Queuring and Building purposes.
Let us imagine that we need to validate if some Patient is eligible for drugs procedures at home provided by nurse.
So this we will need two specifications. If they are both satisfied we could say that this patient is eligible for drugs procedures at home.
First specification
}
Second specification
As you guess ISpecification interface looks like:
Usage could look like:
You could say that we can put all verification in our method FetchPatientsForVisitWithDrugs. Yes, but this is not right way, because your specifications could be used in different locations and also if see this from DDD perspective you always need to bring concept things into the light.
Another question: Don’t you see this systax
if(drugsSpec.IsSatisfiedBy(patient) && nurseVisit.IsSatisfiedBy(patient))
to be boring systax? Yes, especially if you have many specifications.
Let us improve our design.
First we will add some methods to our interface like here:
}
And also will add CompositeSpecification which will be abstract base class for our two existing.
Let’s move to our existing specifications and how they changed with our new design:
}
This all gives us ability to have build specifications quering in more sweet way.
New Usage
Now we work with this new specification as with simple single one: if(specification.IsSatisfiedBy(patient))
With other specifications like OrSpecification and NotSpecification we could build more complicated queries.
For example I will show some possible usage of this in Nhibernate:
Advantages of the Specification:
January 23, 2010 Design Patterns 2 comments
Consider you need to develop some searching engine. Engine will look for different messages that has been sent. Searching process consists with few operations which make sense for each of message, BUT could have some characteristic which differs.
You want to write Searcher, which will allow you encapsulate algorithm of searching, but you also want to leave ability override behavior of some operations for specific messages. How could you accomplish this easily?
This pattern is intuitive as well as realization of it. You will need base class which holds primitive operations and some Template method (Search) which operates with those operations. Each operation could be overridden in derived classes.
I wrote naive implementation of this pattern, because I call primitive operations one by one in my template method. In real world you could hold complex algorithm built on your primitive operations. And you will just need to override parts which differs from standard implemented in base class. Please note that you could make primitive operations abstract. This will require implementation in each derived class.
My example implementation
protected Date DateSent;
protected String PersonName;
protected int ImportanceLevel;
public MessagesSearcher(Date dateSent, String personName, int importanceLevel){
DateSent = dateSent;
PersonName = personName;
ImportanceLevel = importanceLevel;
}
//primitive operations
protected void createDateCriteria(){
System.out.println(“Standard date criteria has been applied.”);
}
protected void createSentPersonCriteria(){
System.out.println(“Standard person criteria has been applied.”);
}
protected void createImportanceCriteria(){
System.out.println(“Standard importance criteria has been applied.”);
}
//TEMPLATE METHOD
public String Search(){
createDateCriteria();
createSentPersonCriteria();
System.out.println(“Template method does some verification accordingly to search algo.”);
createImportanceCriteria();
System.out.println(“Template method verifies if message could be so important or useless from person provided in criteria.”);
System.out.println();
return “Some list of messages…”;
}
}
public class ImportantMessagesSearcher extends MessagesSearcher{
public ImportantMessagesSearcher(Date dateSent, String personName) {
super(dateSent, personName, 3); // 3 means important message
}
//primitive operation overriden
protected void createImportanceCriteria(){
System.out.println(“Special importance criteria has been formed: IMPORTANT”);
}
}
public class UselessMessagesSearcher extends MessagesSearcher {
public UselessMessagesSearcher(Date dateSent, String personName) {
super(dateSent, personName, 1); // 1 means useless message
}
//primitive operation overriden
protected void createImportanceCriteria(){
System.out.println(“Special importance criteria has been formed: USELESS”);
}
}
Following usage:
Produces output:
Standard date criteria has been applied.
Standard person criteria has been applied.
Template method does some verification accordingly to search algo.
Special importance criteria has been formed: IMPORTANT
Template method verifies if message could be so important or useless from person provided in criteria.
Hope my example was not painful to understand. Honestly I do not see it to be 100% clear example on this pattern, but I think I did a great job on this. Of course you could find dozens of examples of it over internet. But this one is mine and it have put something in my mind.
January 17, 2010 Design Patterns, Java 10 comments
Imagine that you are developing some gaming software. Your write Web client and on each of response you are parsing entire XML to get your game Units. You have some set of types of Units, for example 50 different animals, but when you parse your XML you can get dozens of instances of the same Unit and few dozens of instances of other Unit.
If User of the game is very passionate gamer, he could send requests very frequently. In this case your application will be creating dozens of instances for each of the Unit. But, your units have some static descriptions. For example, Dragon has Attack, initial Health level, and also you need to keep image of the dragon in the object of Dragon.
This all lead to intensive and not efficient memory usage. How could you share common information for all types of Units without creating instances for each individual Unit?
1) Simplest way with creating objects each time.
We have base class Unit:
And two derived – Dog and Dragon. To make those objects more weightfull I added to them picture. In my case that is only very long string.
And our parser executes code which looks like:
We want to create only 150 Dragons and 600 Dogs and this takes 28 Mb of memory.
2) How does FlyWeight work?
Lets introduce UnitsFactory. Responsibility of this factory is to manage creation of the concrete flyweight objects (Dogs and Dragons). It verifies if the object has been already created and in this case it just returns created and if not it creates new one and returns it. See:
Lets take a look on UML diagram of our code:
UnitsFactory corresponds to FlyweightFactory, Unit – for Flyweight. Dog, Dragon corresponds to concrete Flyweights in the GoF FlyWeithgt naming.
Now we will do change to our parser to use Factory and will see how much of memory will it take.
But now we are going to create 1500 Dragons and 60000 Dogs, probably your gamer is quite more quick as you think.
And this takes only about 5 Mb of memory:
What have I learned regarding to of Java?
I know that corresponding to C# Dictionary is Map in Java, and there are few concrete maps like on this good picture:
Hope this was a good story!
Go to: My Design Patterns Table
January 16, 2010 Design Patterns, Java 2 comments
Imagine that you need to develop application for shipping Orders. Your Orders could be in few states: New Order, Registered, Granted, Shipped, Invoiced, Cancelled.
And there are some rules which allow your Order to migrate to another state. This means that for example you cannot ship not registered Order.
Also there are some behavioral rules. For example you cannot add new Product to your Order when it is in Cancelled state. Also behavioral rules could mean changes in state.
How could you accomplish this requirements easily?
We could encapsulate behavior which belongs to current object’s state into separate classes derived from some parent class. Each of the concrete will be responsible for allowing changing state from one to another.
State Pattern UML
How does it work?
At first our Order class has a reference to its _state, to have more real example Order also has _products.
private OrderState _state;
private List<Product> _products = new ArrayList<Product>();
public void setOrderState(OrderState state){
_state = state;
}
Order delegates some state-specific requests to the current state.
– If the current state is Granted, it changes Order‘s state to Shipped and if needed do some surrounded work or delegates it.
This code represents concrete implementation of the OrderState. Constructor of base class has Order parameter, so this allows us have reference to holding Order: _order in derived classes.
public Granted(Order holdingOrder) {
super(holdingOrder);
}
public void ship(){
_order.doShipping();
//next line changes Order’s state
_order.setOrderState(new Shipped(_order));
}
If you are care what method ship() is doing in Order class it could be like shipping :).
– If current state is Registered, most likely that class has no implementation of method ship(), it has only addProduct(), grant(), and cancel(). So method of super class will be called. OrderState has all bulk of methods but they all throw exceptions, which says that changing state in current situation is not allowed.
protected Order _order;
public OrderState(Order holdingOrder){
_order = holdingOrder;
}
public void ship(){
raiseNotAllowableOperation(“ship”);
}
//other methods like register(), grant(), etc… here..
//they look like the ship() looks
private void raiseNotAllowableOperation(String operation) throws IllegalStateException {
String stateName = this.getClass().getName();
System.out.println(“ERROR: Operation [“+operation+“] is not allowed for current order state: “ + stateName);
//of course in real system you will probably throw exception
//throw new IllegalStateException(“This operation is not allowed for current order state.”);
}
Example of Usage of Order class
Now we navigating to customer code. Our OrderingSystem creates new Order, adds some beer as product and all in correct way:
Output:
Ok, now we added code, which tries to add more beer when order has been already shipped.
Output:
Other ways to solve problem without State Pattern
One of the disadvantages of this you could see many of the classes needed to have:
Yes, but this is the way to greatly encapsulate your behavior. Also there are other ways to resolve problem. For example usage of the table [state|method|state] which is populated with all allowable transitions. You could also resolve issue with having switch-case method. About all of this you could read in Jimmy Nilsson’s book “Applying Domain-Driven Design and Patterns“.
What have I learned?
I hope you enjoyed this story.
Go to: My Design Patterns Table
January 15, 2010 Design Patterns 3 comments
Imagine that you need some global logging system in your application.
You need to be able log your messages to some file at any point of your application, but also you need to numerate your messages.
How can you accomplish this?
Class which is represented below is example of Singleton Desing Pattern.
private LoggerSingleton(){}
private int _logCount = 0;
private static LoggerSingleton _loggerSingletonInstance = new LoggerSingleton();
public static LoggerSingleton GetInstance(){
return _loggerSingletonInstance;
}
public void Log(String message){
System.out.println(_logCount + “: “ + message);
_logCount++;
}
}
You are going to start execute your doHardWork method and you want to log that you just started doing hard work and what occured doing it.
So your functional system could look like below:
logger.Log(“Hard work started…”);
processor.processTo(5);
logger.Log(“Hard work finished…”);
}
As you see there is some class called HardProcessor. We should not really care how it works. All about we should care is that when it is created we want to log this and also we want to log when it is done with some calculations.
public HardProcessor(int start){
_start = start;
LoggerSingleton.GetInstance().Log(“Processor just created.”);
}
public int processTo(int end){
int sum = 0;
for(int i = _start; i <= end; ++i){
sum += i;
}
LoggerSingleton.GetInstance().Log(“Processor just calculated some value: “ + sum);
return sum;
}
}
Here is output of your programm:
I wrote this example when was in train with my friend. And I showed him my story and he said that I wrote Monostate. -“Me? Where?”. We took a look at my code and the only one variable I was using _logCount was static initially.
What is the difference between Singleton and Monostate?
Singleton is way to ensure that class has only one instance. Monostage if see globally on it do the same as GOF Singleton. All variables of it are static and this allows you to have many instances of monostate, but of course they will share the same data.
This also resolves many issues with multiconcurrecy usage of Singleton.
Lets take a look at my example once again. Could be that your logger is no so trivial, maybe on start of application you want to open some log file and get latest message number, so logger will continue to write to file with correct numbers.
Also your application is not so trivial. Maybe you are accessing your Singleton not only from just different places in your code but from different threads.
But since your constructor interacts with IO it takes time to construct your instance. So GetInstance() in reality in such situation could create TWO instances. Not really good for your application.
For our luck there are many ways to resolve this issue. Commonly we use Double-Checked Locking.
private ThreadSafeLoggerSingleton() {
//reads data from some file and gets latest number of message
//_logCount = got value here…
}
private int _logCount = 0;
private static ThreadSafeLoggerSingleton _loggerInstance;
public static ThreadSafeLoggerSingleton GetInstance(){
if (_loggerInstance == null) {
synchronized (ThreadSafeLoggerSingleton.class) {
if (_loggerInstance == null)
_loggerInstance = new ThreadSafeLoggerSingleton();
}
}
return _loggerInstance;
}
public void Log(String message) {
System.out.println(_logCount + “: “ + message);
_logCount++;
}
}
The way is not single and not all implementations of the DCL work! Read this good article on this: http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
Also as you see in method Log I’m using variable of my class and do operation on it, which is almost atomary. But if operations will be more complex you will need synchronization there also.
Go to: My Design Patterns Table
January 15, 2010 Design Patterns No comments
Creational Patterns
|
Structural Patterns
|
Behavioral Patterns
|
---|---|---|
Abstract Factory | Adapter | Chain of Responsibility |
Builder | Bridge | Command |
Factory Method | Composite | Interpreter |
Prototype | Decorator | Iterator |
Singleton | Facade | Mediator |
Flyweight | Memento | |
Proxy | Observer | |
State | ||
Strategy | ||
Template Method | ||
Visitor |
*As of Jan 2010 this blog post has this at the beginning:
[One of the goals for this year is to familiarize with Java. To accomplish this I have two possilities. First
one is my Master Diploma work in which I’m going to significantly
improve calculations in Self-Organizing Maps with efficient usage of
concurrency in Java Second one is my decision to write my own all of the GoF Design Patterns. And as you guess I want do this with Java. Next
table represents collection of Design Patterns and will have links to
my posts on each of the Pattern. I will fill it soon, no doubts.]