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


Generics performance vs. non-generics performance

January 22, 2010 .NET, Opinion 7 comments

Today I was reading some book on the .net development and found there interesting thing.

Guy explains “Why to use Generics?
He wrote that Frameworks 1.0 and 1.1 did not support Generics, so developers were using Object.
He says, that generics offers two significant advantages over using the Object class:
1) Reduced run-time errors
That is because type-safety.
2) Improved perfomance
Casting requires boxing and unboxing, which slows performance. Using of Generics doesn’t require casting or boxing, which improves run-time performance.

And then funny thing…
He put a box which looks like:

Real Word
(his name)
I haven’t been able to reproduce the performance benefits of generics;
however, according to Microsoft, generics are faster than using
casting. In practice, casting proved to be several times faster than
using a generic. However, you probably won’t notice performance
differences in your applications. (My tests over 100,000 iterations took only a few seconds.) So you should still use generics because they are type-safe.

OMG! I could not believe in his words. As per me this should be BULLSHIT, unless I 100% missed something there.

Test

I wrote a really quick verification like:

namespace TestGenericsPerfomance
{
    class Program
    {
        internal static void Main(string[] args)
        {
            Stopwatch stopWatch = new Stopwatch();
            //Working with value objects
            //Generic wins 100%
            stopWatch.Start();
            ArrayList nonGenericArrayList = new ArrayList();
            for (int i = 0; i < 10000000; i++)
            {
                nonGenericArrayList.Add(i);//takes Object so boxing is performed here…
            }
            stopWatch.Stop();
            Console.WriteLine(string.Format(“Int32: ArrayList (boxing): {0:0}”, stopWatch.Elapsed.TotalMilliseconds));
            stopWatch.Restart();
            List<Int32> someCustomersIds = new List<Int32>();
            for (int i = 0; i < 10000000; i++)
            {
                someCustomersIds.Add(i);
            }
            stopWatch.Stop();
            Console.WriteLine(string.Format(“Int32: List<Int32> (generic): {0:0}”, stopWatch.Elapsed.TotalMilliseconds));
 
            //Working with reference objects
            //Generic still wins, but not so sure..
            Customer sharedCustomer = new Customer();
            stopWatch.Restart();
            ArrayList nonGenericArrayListCustomers = new ArrayList();
            for (int i = 0; i < 10000000; i++)
            {
                nonGenericArrayListCustomers.Add(sharedCustomer);//no boxing.. jut putting the same reference
            }
            stopWatch.Stop();
            Console.WriteLine(string.Format(“Customer: ArrayList (no boxing): {0:0}”, stopWatch.Elapsed.TotalMilliseconds));
            stopWatch.Restart();
            List<Customer> genericBasedOnInterface = new List<Customer>();
            for (int i = 0; i < 10000000; i++)
            {
                genericBasedOnInterface.Add(sharedCustomer);//just put the same reference in generic list
            }
            stopWatch.Stop();
            Console.WriteLine(string.Format(“Customer: List<Customer> (no boxing): {0:0}”, stopWatch.Elapsed.TotalMilliseconds));
        }
        private class Customer
        {
            public string Name = “Andriy Buday”;
            public string Buy(string what)
            {
                return “I’m glad I bought that.”;
            }
        }
    }
}

And the result is:

Int32: ArrayList (boxing): 2443
Int32: List<Int32> (generic): 294
Customer: ArrayList (no boxing): 586
Customer: List<Customer> (no boxing): 315
Press any key to continue . . .

As you see generics are much faster. Also I searched over internet and found a lot of different stuff that says that generics provide better performance.

My Opinion

You would said what kind of book do I read. Is it “C# for Complete Dummy“?
No, that is Microsoft’s training Kit for exam 70-536.
Even if this was a book “C# for Dummy” it should not contain mistakes. And even if this is a book for kids it should not contain wrong thing. Yea.. it could be very simple, but not wrong!

I thought to write e-mail to that guy, but then decided that there is no need in this.

Just be careful when you read books and others thoughts, even mine :)


7 comments


Complex Custom Configuration

January 19, 2010 .NET 1 comment

Have you ever faced with need to have your custom configuration?

Probably yes, on MSDN you can find a good example on custom configuration here.
That example was not 100% what I need, since I needed few included one in others collections. Like below:

<?xml version=1.0 encoding=utf-8 ?>
<configuration>
  <configSections>
      <section name=ServicesSettings type=RoadMap.CustomConfiguration.ServicesSection, RoadMap.CustomConfiguration/>
  </configSections>
  <ServicesSettings>
    <Services>
      <add serviceName=Greeter isEnabled=true interval=7>
        <Messages>
          <add messageName=Hello/>
          <add messageName=World/>
        </Messages>
      </add>

      <add serviceName=BadBoy isEnabled=false interval=“10”>
        <Messages>
          <add messageName=Go to/>
          <add messageName=Hell/>
        </Messages>
      </add>

    </Services>
  </ServicesSettings>
</configuration>

As you see I want to get list of services which of them could be enabled or disabled also it could have interval to send one or many messages, which are also configured.

As you see I already added RoadMap.CustomConfiguration.ServicesSection to map ServiceSettings section to my appropriate class:

ServicesSection

using System.Configuration;
namespace RoadMap.CustomConfiguration
{
    public class ServicesSection : ConfigurationSection
    {
        [ConfigurationProperty(“Services”)]
        public ServicesCollection Services
        {
            get { return ((ServicesCollection)(base[“Services”])); }
        }
    }
}

Next you will probably will want to take a look is ServicesCollection:

ServicesCollection

using System.Configuration;
namespace RoadMap.CustomConfiguration
{
    [ConfigurationCollection(typeof(ServiceElement))]
    public class ServicesCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ServiceElement();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ServiceElement)(element)).Name;
        }
        public bool ContainsKey(string key)
        {
            var element = BaseGet(key);
            return element != null ? true : false;
        }
        public ServiceElement this[int idx]
        {
            get
            {
                return (ServiceElement)BaseGet(idx);
            }
        }
        public ServiceElement this[object key]
        {
            get
            {
                return (ServiceElement)BaseGet(key);
            }
        }
        public void Add(ServiceElement element)
        {
            base.BaseAdd(element);
        }
    }
}

ServiceElement

using System;
using System.Configuration;
namespace RoadMap.CustomConfiguration
{
    public class ServiceElement : ConfigurationElement
    {
        [ConfigurationProperty(“serviceName”, DefaultValue = “Greeter”, IsRequired = true)]
        [StringValidator(InvalidCharacters = “~!@#$%^&*()[]{}/;'”|\”, MinLength = 1, MaxLength = 60)]
        public String Name
        {
            get
            { return (String)this[“serviceName”]; }
            set
            { this[“serviceName”] = value; }
        }
        [ConfigurationProperty(“isEnabled”, DefaultValue = true, IsRequired = false)]
        public bool IsEnabled
        {
            get
            { return (bool)this[“isEnabled”]; }
            set
            { this[“isEnabled”] = value; }
        }
        [ConfigurationProperty(“interval”, DefaultValue = “10”, IsRequired = false)]
        [IntegerValidator(ExcludeRange = false, MaxValue = 100, MinValue = 1)]
        public int Interval
        {
            get
            { return (int)this[“interval”]; }
            set
            { this[“interval”] = value; }
        }
        [ConfigurationProperty(“Messages”)]
        public MessagesCollection Messages
        {
            get { return ((MessagesCollection)(base[“Messages”])); }
        }
    }
}

As you see it has Messages property which is again collection (similar to ServicesCollection) of MessageElements:

MessageElement

using System;
using System.Configuration;
namespace RoadMap.CustomConfiguration
{
    public class MessageElement : ConfigurationElement
    {
        [ConfigurationProperty(“messageName”, DefaultValue = “hi”, IsRequired = true)]
        [StringValidator(InvalidCharacters = “~!@#$%^&*()[]{}/;'”|\”, MinLength = 1, MaxLength = 60)]
        public String Name
        {
            get
            { return (String)this[“messageName”]; }
            set
            { this[“messageName”] = value; }
        }
    }
}

To ensure you that this works as expected just take a look on following screenshots:

We have one Greeter service:

It has two messages and second one is “World”:

Hope you could just copy-paste my code and also add MessagesCollection and you are done, just change naming to your needs.


1 comment


IDENTITY_INSERT is already ON for table [Table_Name]

January 19, 2010 Errors, SQL 20 comments

I was editing some script in SQL Server Management Studio.

And then suddenly this error appeared:

IDENTITY_INSERT is already ON for table [Table_Name]

So, how did I come to this error?

My script looked like one below:

SET IDENTITY_INSERT [TABLE_NAME] ON

–insert statements

failure on one of inserts because of not existing column

SET IDENTITY_INSERT [TABLE_NAME] ON

 

The script failed on one of the inserts, because of a missing column.

I added a column to fix the problem but then I started getting this error: IDENTITY_INSERT is already ON for table [Table_Name].

I tried to run inserts independently but error persisted.

Why does it happen?

IDENTITY_INSERT works in scope of one session. If you read corresponding MSDN page it says: “At any time, only one table in a session can have the IDENTITY_INSERT property set to ON.”

How to solve?

You just need another session. I simply reconnected to the same database and it run without any issues.

Of course I changed the script to set IDENTITY_INSERT to OFF in the end.


20 comments


I’ve learnt Ruby in Twenty Minutes

January 17, 2010 Ruby 7 comments

Of course not. There is a lot of interesting stuff in Ruby. But at least I tried that quick list here:
http://www.ruby-lang.org/en/documentation/quickstart/

To print something you just need to write puts keyword.

irb(main):001:0> puts “Andriy said something….”
Andriy said something….
=> nil

You could calculate online:

irb(main):002:0> 750*8.05
=> 6037.5

Lets define method to calculate price of one of the Dell notebooks here in Ukraine if price is in Dollars, but you want to know how much it is in Hryvnas.

irb(main):003:0> def exchange(price)
irb(main):004:1>   puts price*8.05
irb(main):005:1>   end
=> nil

Lets use it:

irb(main):006:0> exchange(750)
6037.5

But Ruby is object-orient language. So here is my Exchanger class and I want to initialize it with exchanging rate:

irb(main):001:0> class Exchanger
irb(main):002:1>   def initialize(rate = 8.05)
irb(main):003:2>     @rate = rate
irb(main):004:2>     end
irb(main):005:1>   def exchange(price)
irb(main):006:2>     puts price*@rate
irb(main):007:2>     end
irb(main):008:1>   end
=> nil

@rate is field of that class. Don’t you see that syntax very sweet? I see.

Next, we will create instance of our class with a bit lower rate. And use that instance of class:

irb(main):009:0> ex = Exchanger.new(8.00)
=> #<Exchanger:0x7dd50fc @rate=8.0>
irb(main):010:0> ex.exchange(750)
6000.0
=> nil

“In Ruby, you can open a class up again and modify it. The changes will be present in any new objects you create and even available in existing objects of that class. “
That is amazing as per me, because you could just write code after you have declaration of your class and change intent of it.

You need to try play with Ruby, that is very sweet language!


7 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


Presentation on DDD for my co-workers

January 17, 2010 Success No comments

Among my goals for this year is to become well-known employee in my company. To accomplish this I’m preparing different presentations and looking for some opportunities once they will appear.

On Thursday I provided presentation for my team workers on Domain-Driven Design.
As per me presentation went well, and I much improved my skills doing presentations. I know this at least because we have surveys to evaluate how the presentation went. And rates there were much higher than last time I did presentation on IoC.

I want to list few things that are flying in my mind after that presentation. They are also some tips to how provide effective presentation. (This is not full list, just associated with this presentation.)

DO

  1. Provide the same presentation to your friend. It is great if you have friend who is working in Software Industry also. Actually we have another blog, where we just fixing which stories we made with short agenda.
  2. Imagine your are providing you presentation right now, try to reproduce what you will be saying in your mind. I did this when way on the way to office.
  3. Improve your presentation with restructuring it to the way it will be easily to speak to it.
  4. Have verbose notes to each slide.
  5. Print your story and have it handy on presentation. Just have. I looked there only once.
  6. I kept attention of my audience with collaborating with it, asking questions.
  7. In the end say that presentation was good. Some people could just believe you :)

DO NOT

  1. Don’t wait for answers long. Collaboration with trainees i great, but if you ask question don’t wait long. Start answering yourself.
  2. Don’t ever make people think that you think that they don’t know something. I did one mistake. I said something like “This could be accomplished with FlyWeight design pattern. Do you know what is it?” then we had a bit of silence. But, I’m sure that many people know that pattern. Maybe I asked not clearly. And my mistake “Nothing bad, if you don’t know, the FlyWeight is…”.

REMEMBER

  1. There always be someone who disliked your presentation, maybe few. Why? Because he/she dislike you, but not your presentation. I can do nothing to such people. Just improve yourself and there will be time they will start to respect it (probably you will not have need in respect from such people).
  2. There are always some pessimists. They always find something that was not really good. Just analyze if their observations make sense, and if yes do the best to fix your issues.
  3. In opposite to those people there will be some who will rate your presentation all with max in a minute you sent survey for feedbacks.


No 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