C# is language for my Diploma. It just won. What could I do?

February 21, 2010 C#, Java, MasterDiploma 2 comments

Today I committed initial version of my Diploma Work Sources.

And there are few interesting things regarding to my first commit.

Thing One (Language)

I re-wrote all my last year course work from Java to C#.
And I did it all in about 12 hours. Its just amazing how my developing speed differs in eclipse and Visual Studio IDEs. As I remember same took me 50+ hours with Java + eclipse and I did all without enthusiasm.

I hate writing properties in Java
This is one thing where I do think that Java is kind more verbose than C#. There are some others, like “var”, etc. Microsoft works on improving C# language.

C#

   public double[] Parameters {get; set;}
Java

    private double[] parameters;
    public double[] getParamateres(){
        return parameters;
    }
    public void setParamateres(){
        return parameters;

    }


How important is your knowledge of IDE?

I would say that even more then knowing of language. Nowadays most of  the languages are object-oriented, they all have similar principles and ideas and code looks almost the same. If we talk about C# and Java they are extremely alike.
I’m not very familiar with Java, but I can write Java code easily and if there are some Java specific gaps I quickly fulfill them with google search.
But when we talk about my speed of coding in eclipse IDE – it is really outstanding thing where my capabilities suck.

Code refactoring tool
That is another thing that could significantly increase your productivity. I’m using Resharper 5.0 Beta. Having experience of using it, I can think about what I want to have, but not how to type that.
Live templates that generates me unit test method after I just type “test”. Delivering from interface, I just created, without typing class name. Moving initialization of fields to the class constructor with single command. “Alt+Enter” just thing instead of me in contest of where mouse cursor is located and proposes me decisions.  — these all are things why I love Resharper. I wrote complex architecture with about 40 classes in about 12 hours. It generates what I think.

Thing Two (Architecture)


I improved my Self-Organizing Maps implementation architecture significantly. What is did is having all implemented in really decoupled interfaces. Main learning processor is just like preparing dinner. You just add component and you do have what you want.

        public LearningProcessorBase(
            ILearningData learningData,
            INetwork network,
            ITopology topology,
            IMetricFunction metricFunction,
            ILearningFactorFunction learningFactorFunction,
            INeighbourhoodFunction neighbourhoodFunction,
            int maxIterationsCount)
        {
            LearningData = learningData;
            Network = network;
            Topology = topology;
            MetricFunction = metricFunction;
            LearningFactorFunction = learningFactorFunction;
            NeighbourhoodFunction = neighbourhoodFunction;
            MaxIterationsCount = maxIterationsCount;
        }

What is the benefit?
Now I’m able easily setup few dependency Profiles and experiment with them. So I can play with different activation, neigbourhood, metric and leaning factor functions, at the same time I can use different topologies like matrix and hexagonal.
Also learning process is now really encapsulated and to add Concurrency implementation should be easily.

Thing Three (I have same results with less effort)

To prove that I have same results I’ve used same application of my Kohonen Maps: classification of animals.
Here is input data list of different animals. Each row describes animal’s properties.

Here is result matrix:

Thing Four (Conclusion)

I’m  really sorry that it is boring for me to have my Diploma written on Java. But I really think that my goal is to invent multi-threaded algorithm that could significantly improve SOM calculations. And I feel really comfortable with C#, so I can enjoy research work without spending time on convincing myself that I do need to accomplish all with Java.
But this doesn’t mean that I gave up with learning Java. No – I will continue implementing all GoF Design Patterns on this pretty language – see my table.


2 comments


Lambda Expression or Simple Loop

February 20, 2010 .NET, LambdaExpression, MasterDiploma 6 comments

For my Diploma work I need to calculate distance between two vectors.
For example, Euclidean distance is calculated like:

How could it look if I do have two lists with values?

Something like this:

         public double GetDistance(IList<double> firstVector, IList<double> secondVector)
         {
             double sum = 0;
             for (int i = 0; i < firstVector.Count; i++)
             {
                 sum += (firstVector[i] – secondVector[i]) * (firstVector[i] – secondVector[i]);
             }
             return Math.Sqrt(sum);

But, please take a look how sweet this all could be with Lambda Expression:

         public double GetDistance(IList<double> firstVector, IList<double> secondVector)
         {
             double sum = firstVector.Select((x, i) => (x – secondVector[i]) * (x – secondVector[i])).Sum();
             return Math.Sqrt(sum);
         }

Of course main point of this post is not to show all beauty of LE, but either what did happen after I wrote this Lambda expression. Maniacal interest in what is faster to execute and what is the difference in performance of this two methods appeared in my mind, so I prepared few simple tests.

I’ve ran my tests on 1000000 elements and results were such:

  1. Lambda expressions are quite slower than simple loops.
  2. My test showed that primitive loop is faster in about 15-20%.

Also, I played with VS performance analyzer (Analyze -> Launch Performance Wizard…).
It allows me run one version of code (Lambda) and get detailed report, then run another version of code (Loop) and get another report. After that I’m able to compare results seeing performance improvements. So that is good tool.


6 comments


NHibernate: Projections.RowCount()

February 19, 2010 NHibernate, QuickTip No comments

 What do you see to be wrong with this code?

        public bool RuleExists(string ruleName, string documentName)
        {
            var result = Session.CreateCriteria(typeof(Rule)“r”)
                //some aliaces 
             
                .SetProjection(Projections.RowCount())

                .Add(Restrictions.Eq(“r.Name”, ruleName))
                //other restrictions
                .List();

            return result.Count > 0;
        }


At first I did not see any issues with it so I copied it and changed a bit for my another query. But current method is wrong. I discovered this with UTs.

First, Projections.RowCount(generates COUNT(*) in select statement.

This is query, which I got from my new Unit Tests: RuleExists_HitsDatabase_ThereIsNoRule.

SELECT count(* ) AS y0_
FROM   TBL_RULE this_
       INNER JOIN — some joins here
     
WHERE  this_.NAME = ‘absolultely_incorrect_rule_name’ /* @p0 */
       AND — other conditions 

Result of this query is number of rows like on picture below:

So, verification return result.Count > 0is absolutely incorrect.
I’ve chagned it to return (int)result[0] > 0;

Moral:
Do not be lazy to write Unit Tests both for success and failure sceneries.


No comments


Few NHibernate hints on Query Criteria

February 15, 2010 NHibernate, QuickTip No comments

ORDER BY


To add “order by” to your criteria you need this statement.
.AddOrder(Order.Asc(“Priority”))

TOP


To add “top 10” to your criteria you need this statement
.SetMaxResults(10)

Criteria

So code about which I’m talking could look like:

        public IList<Customer> FetchTopPriorityCustomers()
        {
            var result = Session.CreateCriteria(typeof(Customer))
                .SetFetchMode(“CustomerStatusType”FetchMode.Eager)
                .Add(Expression.Eq(“CustomerStatusType.CustomerStatusTypeID”, (Int32)CustomerStatusType.Created))
                .SetResultTransformer(new DistinctRootEntityResultTransformer())
                .AddOrder(Order.Asc(“Priority”))
                .SetMaxResults(10)
                .List<Customer>();
            return result;
        }

SetResultTransformer or “Why did I get 5 results instead of 10?”

So you expect to have top 10 priority Customers with status Created.
In scope of my current task it was needed to add priority to this query, so I decided to unit test it of course.
In Debug I found that there are actually 5 results in resulting collection.

That is because generated SQL generates result which contains duplicated CUSTOMER_IDs, that is because I have join-s there. But then why did not I get 10 duplicated Customers? Because query has ResultTransformer which is applied after SQL has been ran. (That is 100% since I took a look at generated SQL via NHibernateProfiler).

So .SetResultTransformer(new DistinctRootEntityResultTransformer()) is removing of all duplicated entries of my root entity (Customer).

Good explanation to this you can find here.


No 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


Речі необхідні, щоб стати успішним програмістом

February 10, 2010 Success, Ukrainian 4 comments

This post is in Ukrainian and is translation to the Things you need to remember to become successful developer

1. Не переставайте вчитися

Я припускаю, що ви навіть б не читали цей пост, якщо б не мали хоча б елементарної освіти, і ви б навіть не хотіли знати як стати успішним програмістом без вищої освіти. То ж якщо ви зараз програміст навіщо зупинятися вчитися?
Це просто недозволено. Одна важлива річ тут: Стояти на одному місці не означає, що ви стоїте на місці – це означає що ви рухаєтеся назад. Просто рухатися вперед не означає що ви рухаєтеся вперед – це лишень означає, що ви не загубилися із невдахами десь в кінці. Щоб просуватися вперед вам слід вчитися постійно – не просто рухатися, а БІГТИ.
Ось мій короткий список, що підпадає під цей пункт:
Читайте книги
Підпишіться на RSS і читайте різні статті
Пробуйте різні мови програмування і речі, про які ви чули
Ходіть на семінари і готуйте власні презентації
Вчіть будь-що, що може вам допомогти просуватися
Вчіть інших, так як це вчить вас

2. Визначте вашу ціль і тримайтеся правильної дороги

Я думаю що важко бігти якщо не знати куди бігти. Основне завдання полягає в тому, щоб чітко уявляти свою ціль. Ваша ціль повинна бути довготермінова і велика. І після того як у вас вже є бачення своєї мети візьміть і розбийте її на дрібні завдання – тобто побудуйте свою карту до успіху. Вам слід скласти список завдань, які ви ПОВИННІ виконати за місяць, або за рік. Як тільки ви його маєте, просто чітко слідуйте за ним.

3. Будь-які проблеми є можливостями

В буденній роботі ви завжди стикаєтеся із різними траблами. Ви отримуєте нові завдання або звіти про баги від тестерів. Ви отримуєте нові проекти від Проджект менеджерів. Ваш співробітник запитує про допомогу. Вам потрібна допомога. Це все приклади проблем. І справді важливе питання тут таке: як ви зустрічаєте їх? Ви можете сказати «Ой, але так я не позбавлюся від дурної надоїдливої роботи». Ви тут абсолютно не праві. Запам’ятайте, що ваші боси будуть раді дати вам більш складну роботі як тільки побачать, що ви справляєтеся із поточними завданнями.

4. Будьте позитивно налаштовані

Ви повинні дивитися на все позитивно. Якщо ви виявили, що зробили помилку просто сприйміть це легко – кожен робить помилки. Вам подобаються люди, які ниють коли у них проблеми? Як ви думаєте ви будете виглядати у чужих очах, якщо ви скажете: «Так, хлопці, я це зробив – я це вирішу, дайте мені хвилинку» і опісля ви повертаєтеся і починаєте фіксати вашу помилку із усмішкою на лиці. Як тільки ви вирішите  проблему ви будете просто щасливі.
Ваша дорога є хорошою і ви швидко рухаєтеся вперед. Ніколи, ніколи не думайте що ви не досягнете своєї цілі – ось суть цього пункту.

5. Знайдіть наставника

Це не означає, що вам потрібна людина, яка буде вам допомагати робити вашу роботу – бо це просто вчитель або ж більш досвідчений розробник. Це означає що вам потрібна людина, яка знаходиться там, де ви хочете бути. Вам потрібно брати приклад із цієї людини. Якщо ця людина недостатньо високо – просто знайдіть когось по серйозніше. Також майте друзів які будуть вам допомагати рухатися по шляху. Або просто користуйтеся підтримкою жінки або дівчини.

6. Ставайте відомими

Якщо ви не покажете іншим, що ви крутий і що ви заслуговуєте більше, як вони будуть про це знати? Є просте рішення – почніть вести блог, запитуйте і відповідайте на питання, переконайтеся що гугл знає вас. Поширюйте своє знання у вашій команді і на проекті. Якщо ви вивчили щось нове, то чому б не поділитися цим? Ви забудете ці нові речі, якщо ви не будете їх пробувати.

7. Слідкуйте за виконанням ваших завдань, будьте певні, що ви й досі на шляху

Час від часу слід перевіряти чи ви робите все правильно. Впевніться, що ви виконуєте поставлені задачі. Якщо ні, то швидко знайдіть причини і працюйте над ними. Знайдіть свої слабкі сторони і змагайтеся із ними. Це може звучати смішно, але я знаю хорошого програміста із добрими теоретичними знаннями, але його швидкість набору коду просто жахлива. Чому? Тому що в нього просто жахлива клавіатура і він не хоче провести 10-20 годин за тренажером. Хіба це не тупо? Друже, якщо ти будеш читати цю статтю, пообіцяй що ти переможеш цю слабинку.

8. Робіть гімнастику

Я зробив маленьке само-опитування, коли писав цю статтю. І «Робіть гімнастику» попало у список. Я є досить молодий і проводжу забагато часу за ноутбуком і за іншою машиною на роботі і я не можу заставити себе робити гімнастику. Але це як точіння леза. Є така історія про двох дроворубів які поспорили про те хто зрубає більше дерев. Один дроворуб був здоровий і великий, а інший худий, як я. Сильний був певен, що він переможе, оскільки він рубав дерева всі 8 годин без жодної перерви, а худий робив перериви на 15 хв. кожної години. Але боротьбу виграв худий – він зрубав 150 дерев тоді коли Силач зрубав 100. Секрет полягав у тому, що він точив лезо тоді коли відпочивав. Ваше здоров’я – це ваша сокира і якщо вона буде тупа ви не зможете вирубати собі дорогу до успіху.

Тому нехай всі ваші сокири будуть заточені!


4 comments


Save entity with assigned ID, not generated by NHibernate.

February 3, 2010 NHibernate No comments

I want generate INSERT which include my Primary Key (not generated) by NHibernate. How to map Id column for this?

I have table CUSTOMER where CUSTOMER_ID is primary key.

Table

  

Code:

CREATE TABLE [CUSTOMER](
    [CUSTOMER_ID] [int] NOT NULL,
    [START_DATE] [varchar(30)] NOT NULL,
CONSTRAINT [PK_CUSTOMER] PRIMARY KEY CLUSTERED ( [CUSTOMER_ID] ASC …..

Mapping

Code:

public class CustomerMap : ClassMap<Customer> {
    public CustomerMap()
    {
        WithTable(“CUSTOMER”);
        Id(x => x.CustomerID, “CUSTOMER_ID”);
        Map(x => x.Name, “NAME”);
    }
}

I need to handle assigning of the CustomerID property manually. For
example I created new Customer with CustomerID = 777 and Name
= “Andriy Buday”
.

When I call method Session.Save(customer);
I want NHibernate to generate me SQL like this:

  

Code:

INSERT INTO [CUSTOMER] ([CUSTOMER_ID] ,[NAME]) VALUES (777,‘Andriy Buday’)

Unfortunately I’m getting errors.

Main issue here is that Nhibernate tries to generate ID for me. But I want to save my entity exactly with 777.

Solution

So I need to manually setup my ID property with adding GeneratedBy.Assigned();
Like here:

Code:

Id(x => x.CustomerID, “CUSTOMER_ID”)
      .GeneratedBy.Assigned();


No comments


English Level

February 1, 2010 English, Success 5 comments

Point 6 in my Where Do You Want to Be In a Year? is:

“Improve my English skills to have at least upper-intermediate strong level (according to my company graduating)”

Previous Level: Intermediate
Last year my level was evaluated as Intermediate, but since that time I had a lot of experience of communication with native speakers. So I was pure much sure that my language is improved. I requested reevaluation, which occurred last week.

How was it?
I’ve drank too much coffee before came for my reevaluation, so my voice was a bit hoarse. Not a plus.
We spoke a bit, I mentioned about that I requested this reevaluation and why do I need that. Then she gave me feedback and proposed me to pass some test.

Feedback
Before test she said that my English level is not upper-intermediate definitely :( , and she explained why:
1) I repeated same words to much.
2) I do not use enough  adjectives.
3) My speech is not fluent.
For upper-intermediate my English should be fluent!

Exercise for me
When I speak I should think not only about what I speak, but also how I speak.

Result
Current Level: Intermediate Strong

English courses
Also, I’m eligible  for English courses in my company, so I moved to upper-intermediate course. This means that course could improve my skills to that level, of course if I’ll be a good student. I really need this study, even if it will be taking some time. I know that to compel myself learning that alone will not succeed. I’ve decided that course will help me with this just fine.
 
I’m on the way to have desired level of English, so will learn hard to have
Future Level: Upper-Intermediate Strong


5 comments


Master Diploma: Self-Organizing Maps Parallelization

January 30, 2010 MasterDiploma 1 comment

It’s time to start seriously work on my Master Diploma.

What about is my Master Diploma work?

In Artificial Intelligence we often use neural networks in try to simulate aspects of the biological neural networks. Applicability of these is very wide, it could be smart unit in some video game, or expert subsystem when diagnosis patient. Even your inbox e-mails are filtered with algorithm, which includes neural networks usage.

One great applicability of Self-Organizing Maps (one of the artificial neural networks) is possibility to analyze high-dimensional data, save its topology and translate it to low-dimensional representation which further could be easily analyzed by human brains.

For human being it is hard to work with dozens of input information for different aspects of one thing. For example 100 patients being diagnosing and for each we need 30-40 different measurements. SOM could easily classify data and for output with knowing of some existing diagnosis we can get “Patient – Diagnosis”.

I mentioned something like “with knowing of some existing…”. This means that SOM requires training, which takes execution time. If our application domain is something for military, time could be critical constraint.

In this work I’m going to significantly improve calculations of Self-Organizing Maps with introducing multi-threading improvements.

Project hosting

I already hosted my project with google code:
http://code.google.com/p/andriybudaydiploma/


Code:
The
self-organizing map is a popular unsupervised neural network model for
high-dimensional data analysis. However, the high execution times
required to train the map put a limit to its use in many application
domains, where either very large datasets are encountered and/or
real-time response times are required.

Project is host for implementation of a parallel algorithm, purpose of
which is to significantly improve calculations of standard algorithm.
This is main goal of actual project.

This project represents Andriy Buday’s Master Diploma work.

e-mail me: andriybuday@gmail.com

What do I need to accomplish?

I need to ensure that I understand computations of SOM deeply.
Research over interned for similar works and take them into account.
I’ve decided to write my code from scratch, since I already have some implementation of SOM.
After I’ll have some implementation I need to analyze results I got on different systems.
Improve my knowledge of Java, Concurrency and train my scientific habits. :)

This blog and my Diploma

I was thinking about posting status of my work on Diploma on separate blog or site, but don’t want to have myseft scattered over different locations, so I’ve decided that just tag “Master Diploma” should be enough. I don’t think that it could make sense to hide something from the world or my co-workers or Customers (don’t even think they read my blog). And of course my Diploma is part of my Road To Success.

Please, wish me luck on this!

No doubt I will do the best to take my work to the breakthrough.


1 comment


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