Design Patterns

Decorator

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?

DECORATOR

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’m Mercedes and I’m on my way…
…beep-beep-beep-…

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.


4 comments


Iterator

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



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.

    SoldiersIterator iterator = new SoldiersIterator(earthArmy);
 
    while(iterator.hasNext()){
        Soldier currSoldier = iterator.next();
        currSoldier.treat();
    }

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:

    Army earthArmy = new Army();
 
    Group groupA = new Group();
    for(int i=1; i<4; ++i)
        groupA.addNewSoldier(new Soldier(“Alpha:” + i));
 
    Group groupB = new Group();
    for(int i=1; i<3; ++i)
        groupB.addNewSoldier(new Soldier(“Beta:” + i));
 
    Group groupC = new Group();
    for(int i=1; i<2; ++i)
        groupC.addNewSoldier(new Soldier(“Gamma:” + i));
 
    earthArmy.ArmyHero = new Hero(“Andriy Buday”);
    earthArmy.addArmyGroup(groupB);
    earthArmy.addArmyGroup(groupA);
    earthArmy.addArmyGroup(groupC);

Hero is class derived from Soldier and has only one difference – higher health level:



public class Soldier {  
    public String Name;
    public int Health;
    protected int maxHealthPoints = 100;
 
    public Soldier(String name){
        Name = name;
    }  
 
    public void treat(){
        Health = maxHealthPoints;
        System.out.println(Name);
    }  
}

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.

public class SoldiersIterator {

    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

   SoldiersIterator iterator = new SoldiersIterator(earthArmy);

But generally this logic could be hidden under some Aggregate’s method (like GetEnumerator in .NET). For example I could have this:

    AbstractIterator iterator = AbstractArmy.GetSoldiersIterator();// returns SoldiersIterator

In .NET world we have IEnumerable<T> and IEnumerator<T> interfaces which provides a lot of help in impementing this pattern:

   var list = new List<int>();
   //GetEnumerator is method of IEnumerator (Aggregate)
   var enumerator = list.GetEnumerator();
   //MoveNext method of IEnumerable (Iterator)
   enumerator.MoveNext();

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 :).

My Design Patterns Table


2 comments


Builder

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

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.

Code:

/** Abstract Builder */
public abstract class LaptopBuilder {
    protected Laptop laptop;
   
    public void createNewLaptop(){
        laptop = new Laptop();
    }

    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:

/** Concrete Builder */
public class GamingLaptopBuilder extends LaptopBuilder {
    public void setBattery() {
        laptop.Battery = “6 lbs”;
    }
    public void setHDD() {
        laptop.HDD = “500 Gb”;
    }
    public void setMemory() {
       laptop.Memory = “6144 Mb”;  
    }
    public void setMonitorResolution() {
        laptop.MonitorResolution = “1900X1200”;
    }
    public void setProcessor() {
        laptop.Processor = “Core 2 Duo, 3.2 GHz”;
    }
}

Or if you Customer is business guy and he watches presentations and exel reports in plain:

Code:

/** Concrete Builder */
public class TripLaptopBuilder extends LaptopBuilder {
    public void setBattery() {
        laptop.Battery = “12 lbs”;
    }
    public void setHDD() {
        laptop.HDD = “250 Gb”;
    }
    public void setMemory() {
       laptop.Memory = “2048 Mb”;
    }
    public void setMonitorResolution() {
        laptop.MonitorResolution = “1200X800”;
    }
    public void setProcessor() {
        laptop.Processor = “Celeron 2 GHz”;
    }
}

To manage steps to build your Laptop basing on the answer you need Director:

Code:

/** Director */
public class BuyLaptop {
    private LaptopBuilder laptopBuilder;
   
    public void setLaptopBuilder(LaptopBuilder lBuilder){
        laptopBuilder = lBuilder;
    }
   
    public Laptop getLaptop(){
        return laptopBuilder.getMyLaptop();
    }
   
    public void constructLaptop(){
       
        laptopBuilder.createNewLaptop();
       
        laptopBuilder.setMonitorResolution();
        laptopBuilder.setProcessor();
        laptopBuilder.setMemory();
        laptopBuilder.setHDD();
        laptopBuilder.setBattery();
    }
}

Here we have usage code.

//Your system could have bulk of builders
TripLaptopBuilder tripBuilder = new TripLaptopBuilder();
GamingLaptopBuilder gamingBuilder = new GamingLaptopBuilder();

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:

Laptop: 1900X1200, Core 2 Duo, 3.2 GHz, 6144 Mb, 500 Gb, 6 lbs

Easy, simple and great pattern. 

What have I learned regarding of Java?
Nothing special, just how to format strings:

Code:

System.out.print(String.format(“Laptop: %s, %s, %s, %s, %s”, MonitorResolution, Processor, Memory, HDD, Battery));


No comments


Specification

January 25, 2010 Design Patterns 3 comments

SPECIFICATION

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

    public class EligibleForDrugs : ISpecification
    {
        public bool IsSatisfiedBy(Patient patient)
        {
            return patient.IsActive && patient.HasPayer;
        }

    }
 
Second specification

    public class EligibleForNurseVisit : ISpecification
    {
        public bool IsSatisfiedBy(Patient patient)
        {
            return patient.IsActive && patient.IsAtHome;
        }
    }

As you guess ISpecification interface looks like:

    internal interface ISpecification
    {
        bool IsSatisfiedBy(Patient patient);
    }

Usage could look like:

        public List<Patient> FetchPatientsForVisitWithDrugs(List<Patient> patients)
        {
            var eligiblePatients = new List<Patient>();
            ISpecification drugsSpec = new ElegibleForDrugs();
            ISpecification nurseVisit = new ElegibleForNurseVisit();
            foreach (var patient in patients)
            {
                if(drugsSpec.IsSatisfiedBy(patient) && nurseVisit.IsSatisfiedBy(patient))
                {
                    eligiblePatients.Add(patient);
                }
            }
            return eligiblePatients;
        }

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:

    public interface ISpecification
    {
        bool IsSatisfiedBy(Patient patient);
        ISpecification And(ISpecification secondSpec);
        ISpecification Or(ISpecification secondSpec);
        ISpecification Not(ISpecification secondSpec);

    }

And also will add CompositeSpecification which will be abstract  base class for our two existing.

    public abstract class CompositeSpecification : ISpecification
    {
        public abstract bool IsSatisfiedBy(Patient patient);
        public ISpecification And(ISpecification secondSpec)
        {
            return new AndSpecification(this, secondSpec);
        }
        public ISpecification Or(ISpecification secondSpec)
        {
            return new OrSpecification(this, secondSpec);
        }
        public ISpecification Not(ISpecification secondSpec)
        {
            return new NotSpecification(secondSpec);
        }
    }
Classes returned by different method of this new CompositeSpecification are used to combine few specifications in order to build new complicated one. They could look simple like this AndSpecification class:
    public class AndSpecification : CompositeSpecification
    {
        private ISpecification firstOne;
        private ISpecification secondOne;
        public AndSpecification(ISpecification firstSpec, ISpecification secondSpec)
        {
            firstOne = firstSpec;
            secondOne = secondSpec;
        }
        public override bool IsSatisfiedBy(Patient patient)
        {
            return firstOne.IsSatisfiedBy(patient) && secondOne.IsSatisfiedBy(patient);
        }
    }

Let’s move to our existing specifications and how they changed with our new design:

    public class EligibleForDrugs : CompositeSpecification
    {
        public override bool IsSatisfiedBy(Patient patient)
        {
            return patient.IsActive && patient.HasPayer;
        }

    }

This all gives us ability to have build specifications quering in more sweet way.
New Usage

            ISpecification specification = new EligibleForDrugs()
                                           .And(new EligibleForNurseVisit());

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:

        public DetachedCriteria PatietQuery(DetachedCriteria criteria)
        {
            criteria.Add(criteria.EqualTo(“patient.IsActive”, true));
            criteria.Add(
                    Expression.Not(
                        Expression.Or(
                            Expression.Eq(“patient.Type”, PatientStatus.Discharge),
                            Expression.Eq(“patient.Type”, PatientStatus.Death)
                        )
                    )
                );
            return criteria;
        }

Advantages of the Specification:

  • Specification declares requirements to the output but do not expose how those results are reached.
  • Rules are defined explicitely. This means that developer could know what to expect from the specification even without knowledge how that is realized.
  • You get flexible interface, which could be easily enhanced. You also could build your composite specifications for queuring.
  • Another good advantage is possitility to test everything easily. You just define fail, non-fail states of the object and verify by checking boolean result.


3 comments


Template Method

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?

TEMPLATE METHOD

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

//base class
public class MessagesSearcher {

    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:

MessagesSearcher searcher = new UselessMessagesSearcher(null, “Sally”);
searcher.Search();
searcher = new ImportantMessagesSearcher(null, “Killer”);
searcher.Search();

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: USELESS
Template method verifies if message could be so important or useless from person provided in criteria.

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.


2 comments


FlyWeight

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?

FLYWEIGHT

1) Simplest way with creating objects each time.

We have base class Unit:
 

public class Unit {
    protected String name;
    protected int health;
    protected String picture;
   
    public void setName(String name) {
    this.name = name;
    }
    public String getName() {
    return name;
    }
    public void setHealth(int health) {
    this.health = health;
    }
    public int getHealth() {
    return health;
    }
    public void setPicture(String picture) {
    this.picture = picture;
    }
    public String getPicture() {
    return picture;
    }
}

 
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.

public class Dog extends Unit{
    public Dog(){
        name = “dog”;
        health = 30;
       
        for(int i = 0; i < 100; ++i)
            picture += “I
don’t want to load actuall image, but if we will be creating a lot of
strings on each of the Unit this could be very resrouce taking
operation.”
;
    }
}


And our parser executes code which looks like:

public class Parser {
    public ArrayList<Unit> parse(){
   
    ArrayList<Unit> result = new ArrayList<Unit>();

    for(int i = 0; i < 150; ++i)
        result.add(new Dragon());
   
    for(int i = 0; i < 600; ++i)
        result.add(new Dog());
   
    System.out.println(“Dogs and Dragons are parsed.”);
   
    return result;
    }
}

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:

public class UnitsFactory {
   
    private static Map<Class, Unit> _units = new WeakHashMap<Class, Unit>();
       
    public static Dog createDog(){
    Class dogClass = Dog.class;
   
    if(! _units.containsKey(dogClass))
        _units.put(dogClass, new Dog());
   
    return (Dog) _units.get(dogClass);
    }
   
    public static Dragon createDragon(){
    Class dragonClass = Dragon.class;
   
    if(! _units.containsKey(dragonClass))
        _units.put(dragonClass, new Dragon());
   
    return (Dragon) _units.get(dragonClass);   
    }
}

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.

    for(int i = 0; i < 1500; ++i)
        result.add(UnitsFactory.createDragon());
   
    for(int i = 0; i < 60000; ++i)
        result.add(UnitsFactory.createDog());
 

       
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 


10 comments


State

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?

STATE
Allowable states
To be more clear about the behavior of our Order, lets take a look on the next statechart diagram:

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

State Pattern UML in application to Order problem

Order State

How does it work?

At first our Order class has a reference to its _state, to have more real example Order also has _products.

public class Order {

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.

public void ship(){
    _state.ship();
}

 – 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 class Granted extends OrderState{

    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 :).

public void doShipping(){
    System.out.println(“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.

public class OrderState {

    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:

public void doHardWork(){
    Product beer = new Product();
    beer.Name = “Lvivske”;
    beer.Price = 78000;
   
    Order order = new Order();
    order.printStateName();
    order.addProduct(beer);
    order.printStateName();
   
    order.register();  
    order.printStateName();
   
    order.grant(); 
    order.printStateName();
   
    order.ship();  
    order.printStateName();
   
    order.invoice();   
    order.printStateName();
}

Output:

Order state: designpatterns.state.NewOrder
Product addeding calculation…
Order state: designpatterns.state.NewOrder
Registration…
Order state: designpatterns.state.Registered
Granting…
Order state: designpatterns.state.Granted
Shipping…
Order state: designpatterns.state.Shipped
Invoicing…
Order state: designpatterns.state.Invoiced

Ok, now we added code, which tries to add more beer when order has been already shipped.

    order.ship();  
    order.printStateName();
   
    //trying to add more beer to already shipped order
    order.addProduct(beer);
    order.printStateName();

Output:

Order state: designpatterns.state.NewOrder
Product addeding calculation…
Order state: designpatterns.state.NewOrder
Registration…
Order state: designpatterns.state.Registered
Granting…
Order state: designpatterns.state.Granted
Shipping…
Order state: designpatterns.state.Shipped
ERROR: Operation [addProduct] is not allowed for current order state: designpatterns.state.Shipped

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?

  • Java has no “virtual” keyword, that is because all methods are virtual. Make sense, cause in C# it is often needed to write huge amount of that word.
  • I discovered few Exceptions that Java has, for example IllegalStateException.
  • I was not able to easily figure out what to use instead of “:” in declaration of derived classed. Now I know “extends“.
  • I improved my UML skills with practicing drawing them.

I hope you enjoyed this story.

Go to: My Design Patterns Table


2 comments


Singleton

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?

SINGLETON

Class which is represented below is example of Singleton Desing Pattern.

public class LoggerSingleton {

    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:

public static void doHardWork() {
    LoggerSingleton logger = LoggerSingleton.GetInstance();
    HardProcessor processor = new HardProcessor(1);

    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 class HardProcessor {
   
    private int _start;

    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:

0: Processor just created.
1: Hard work started…
2: Processor just calculated some value: 15
3: Hard work finished…

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.

public class ThreadSafeLoggerSingleton {

    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


3 comments


Design Patterns

January 15, 2010 Design Patterns No comments

[Update for the 5/31/2011]* 
Here below is what I call “My design patterns table”. It has links to my explanation of 23 GoF design patterns that were initially published in 1994 in book Design Patterns: Elements of Reusable Object-Oriented Software, that has changed the way people think about programming and applying standard solutions to common problems.
I tried to keep my examples of patterns very simple and in the way, that person reading example can build associations with real or close to real world situations. I also translated all of the examples into Ukrainian and at the moment in process of assembling small e-book. Hope you enjoy my examples.

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.]


No comments