Tuesday, 28 January 2014

How To....

The Template Method Pattern :
"Defines the skeleton of an algorithm in a method,defering some steps to subclasses.Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure"
Principle used : The Hollywood Principle i.e "Don't call us,we'll call you" (ha ha "never")
Here High level components determine "when"  lower level components are needed and how they are used, but  letting low level components to hook themselves into the system.
- head first design patterns book.
http://www.oodesign.com/template-pattern.html
Couple of months back I was annoyed by the dailymail article about how men look at  women.
For your information this is the article.
What are you staring at? Scientists reveal how our brain sees men as people, but women as body parts (and it's not just men who do it)

Read more: http://www.dailymail.co.uk/sciencetech/article-2179164/Double-vision-How-brains-men-people-women-body-parts.html#ixzz2rgMM8Kr7.
Let us think of a project for the men to create perfect woman.Let  "PerfectWoman" is an abstract class.
GarysPerfectWoman, PetersPerfectWoman are two concreate implementations.
public abstract class PerfectWoman{
// here you have some stuff to do. you need a media tackers,a graphic,a canvas ...., I only give general ideas it is not the full implementation

final void drawPerfectWomanImage(){

    drawHeadImage();
      drawUpperBodyImage();
     drawLowerBodyImage();
      drawLegImage();
      drawString();//this is the hook which does nothing.
}
      abstract void drawUpperBodyImage();
      abstract void drawLowerBodyImage();
  final void drawHeadImage(){
      g. setImage("kimkardashianheadImage.jpg" ,20.00,20.00,c);/** you never know whose head in that jpg**/
}
   final void drawLegImage(){
    g. setImage("JenniferLopezLeg.jpg",20.0,400.00,c);/** but you never know whose legs are  in that jpg**/
}
    void drawString(){}/** does nothing here , you can name your own name or you can leave this as it is.**/
}
Concreate implementation:
public class GarysPerfectWoman extends PerfectWoman{
// constructors not shown
public void drawUpperBodyImage(){
g.setImage("kieraknightlyUpperbodyimage.jpg",20.0,100.0,c);/** like this you can set your own picture.**/
}
public void drawLowerBodyImage(){
   g.setImage("jenniferLopezLowerBodyImage.jpg",20.0,200.0,c);
}
}
now some where in the tester
  PerfectWoman garys = new GarysPerfectWoman();
     garys. drawPerfectWomanImage();/** that draws a perfect woman for Gary , but Gary cannot change the head or leg.(we never let Gary to hurt  the feelings of good women)**/
In this way high level components controls the flow of the program and holds some control over some parts of the program.

title:

How to  draw image of a perfect woman without photoshop but with some guidelines.


Wednesday, 22 January 2014

How To....

The Observer Pattern:
"defines a one-to- many dependency between objects so that when one object change state ,all of its dependents are notified and updated automatically"
Design Priciple used:Strive for loosely coupled designs between objects that interact.
- Head first Design Patterns
The above picture is taken from http://www.oodesign.com/observer-pattern.html

Now is the time to understand life of a celebrity,let us say Wendy. Way back then ,when she wasn't a celebrity, she had only 3 friends. Susy, Loosy(she won't mind if I spelt her name wrong), Jenny. If she had something to say to them she knows how to say to them. Since for Susy, she just have to email her since she works in a office and mobile phone  is not allowed in there. (Her boss is too bossy). For Loosy , she had to text her since she is always outgoing and very busy. For Jenny she has to ring home since she is a house wife. (never checks email or mobile phones).
so if she has to give any updates she has to do
susy.email();
loosy.text();
jenny.ring();
Now she is a celebrity ie she is a subject so that everybody wants to hear her updates. She do not know everyone and she is busy to give everyone her updates. Now what should she do? I think she has to do a "Twitter" account. Everyone who wants to follow her (that is our observers) have to have some common methods so that she doesn't have to know everybody and thier needs. Let us consider one to many relationships and how to make class loosely coupled.Note that this is not our actual real life twitter.(a sort of)
Let us consider "Twitter" is our subject interface(it could be abstract also). Let us say "Follower" is our observer. There might be another interface "Communicator" depending on the needs.
public interface Twitter{
public void follow(Follower fl);
public void removeFollwer(Follower fl);
public void acknowledgeFollowers();
}
public interface Follower{
public void updateStatus(String tweet);
}
public interface Communicator{
public void communicate();
}

public class CelebrityTwitter implements Twitter {
     private ArrayList followers;
      private string tweet;
public CelebrityTwitter() {
    followers = new ArrayList();
}
public void follow(Follower fl){
       followers.add(fl);
}
public void removeFollower(Follower fl){
int k = followers.index(fl);
if (k>=0)
followers.remove(k);
}
public void acknowledgeFollowers(){
for (int i=0;i<observers.size();i++){
Follower follower = (Follower)followers.get(i);
follower.updateStatus(tweet);
}
public void setTweet(String tweet){
this.tweet =tweet;
acknowledgeFollowers();
}
}
Concreate implementation of Follower and Communicator
public class EmailCommunicator implements Follower,Communicator{
private string  tweet;
private Email email;
private Twitter  celebrityTwitter;
public EmailCommunicator(Twitter celebrityTwitter,Email email){
this.celebrityTwitter = celebrityTwitter;
this.email =email;
celebrityTwitter.follow(this);
}
public void updateStatus(String tweet){
this.tweet = tweet;
communicate();
}
public void communicate(){
email.send(tweet);
//phonenumber.sendText(); in case of TextCommunicator()
/**by the way this is not the way you actually send email. for that you have to import all these(
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
and do some more stuff ) **/
}
}
Same way you can have lots of comunicator and Follower combinations.TextCommunicator,VoiceMailCommunicator..... all implement  "Follower" and "Communicator"  with different way of communications in communicate() method.
public class TwitterProfile{
public static void main(String[] args){
Twitter wendyTwitter = new CelebrityTwitter();
Email susyEmail = new Email("susy@email.com");
EmailCommunicator susycommunicator = new EmailCommunicator(wendyTwitter,susyEmail);
..........
TextCommunicator loosyCommunicator = new TextCommunicator(wendyTwitter, loosyphone);
.........
wendyTwitter.setTweet(" I am working on a film");
wendyTwitter.setTweet("I am going home from film  shooting");
........
Now everyone is Happy.   Wendy doesn't have to know everyone, as long as you follow her you get her tweeting updates as you desired.

Hence the title:

How To follow a celebrity without stalking.


Friday, 17 January 2014

How to ......

Strategy Pattern:
"Defines a family of algorithms, encapsulates each one,and makes them interchangeable.Strategy lets the algorithm vary independently from clients that use it."
OO principles used:
1) Encapsulate what varies.
2)Favor composition over inheritence.
3)Program to interfaces, not implementations.
- Head first Design patterns.
When you  hear the word "strategy" , always think of money or money making strategies. After you reading this blog I can assure you that you will never , never forget what is strategy pattern in OO designing.

 The above picture is from http://www.oodesign.com/strategy-pattern.html
Now let us consider a  topic that you all love. Let us consider cricket Players.Let " CricketPlayer" is an abstract class.  Bowler,Batsman,WicketKeeper ... are all concreate implementation of "CricketPlayer" Class. BowlingStrategy, BattingStrategy.... are interfaces.Now  GoodBattingStrategy, BadBattingStrategy,ModerateBattingStrategy are concreate implementations of BattingStrategies. Where as BadBowlingStrategy, GoodBowlingStrategy,ModerateBowlingStrategy are concreate implementations of BowlingStrategies.Oh ya, now what?  ah ha  "Now we can do some match fixing". (according to the money).We can fix the match even  on the spot.
public abstrct class CricketPlayer {
BattingStrategy battingstrategy;
BowlingStrategy bowlingstrategy;
public abstract void description();
public void setBowlingStrategy(BowlingStrategy bw){
     bowlingstrategy = bw;
}
public void setBattingStrategy(BattingStrategy bs){
      battingstrategy = bs;
}
public void doBatting(){
       battingstrategy.doBattingWithStrategy();
}
public void doBowling(){
        bowlingStrategy.doBowlingWithStrategy();
}
public void doFielding(){
System.out.println("everybody can do fielding");
}
// add some more methods if you want to.
  }
Now concreate implemetation of "CricketPlayer"
public class Batsman extends CricketPlayer {
public Batsman(){
      battingStrategy = new GoodBattingStategy();
      bowlingStategy = new BadBowlingStrategy();
}
puplic void description(){
System.out.println("normally I do good batting , but I can't do bowling");
}
// you can set wicket keeping strategy too
}
Now concreate implemetation of "CricketPlayer"
public class Bowler extends CricketPlayer {
public Bowler(){
      battingStrategy = new BadBattingStategy();
      bowlingStategy = new goodBowlingStrategy();
}
puplic void description(){
System.out.println("normally I do good bowling , but I can't do batting");
}
// you can set wicket keeping strategy too
}

these are our interfaces:
public interface BattingStrategy {
public void doBattingWithStrategy();

public interface BowlingStrategy {
public void doBowlingWithStrategy();

Concreate implemementations of strategies.
         public class GoodBattingStratergy implements BattingStratergy{
                          public GoodBattingStratergy(){
                             // set good parameters
                                 //set good minimum  money too
                              }
             public void doBattingWithStrategy(){
                            // use a good algorithem for batting
                        // then  do batting
                 }
}
similar way you can implement other classes too. Differnt algorithmes like lefthand ,righthand , offspin, spinners .... as long as you implement the strategies.
let us see two simulators ie match:
public class GenuineMatch {
   public static void main(String[] args) {
    CricketPlayer  rajeshkootrapalli = new Batsman();
     CricketPlayer sheldoncooper = new Bowler();
     rajeshkootrapalli.doBatting();
      rajeshkootrapalli.doBowling();
       sheldoncooper.doBatting();
        sheldoncooper.doBowling();
}
}
public class  FixedMatch {
   public static void main(String[] args) {
    CricketPlayer  rajeshkootrapalli = new Batsman();
     CricketPlayer sheldoncooper = new Bowler();
   rajeshkootrapalli.setBattingStrategy(new BadBattingStrategy());
     rajeshkootrapalli.doBatting();
      rajeshkootrapalli.doBowling();
      sheldoncooper.setBowlingStrategy(new BadBowlingStrategy());
       sheldoncooper.doBatting();
        sheldoncooper.doBowling();
}
}

This way if you encapsulate algorithems in different classes and we can fix the match on the spot without anybodies' attention or concern.  This is how online gaming works.  All winning strategies or loosing strategies are encapsulated in different classes. You can purchase them according to the money. Good algorithems always costs lots of money.

hence the Title:

  How to make money from Strategy patterns.      

Monday, 13 January 2014

How to...

In this blog I am going to write about decorator pattern of OO designing.
examples :
InputStream:
concreate classes:FileInputStream,StringBufferInputStream,ByteArrayInputStream.
decorator:FilterInputStream:
Concreate decorators:
PushBackInputStream,BufferedInputStream,DataInputStream,
LineNumberInputStream
Design Principle :Classes should be closed for modifications but open for extensions. 

Decorator : "Attach additional responsibilities to an object dynamically.Decorators provide a flexible alternative to subclassing for extending functionality" - The book Head First Design Patterns.

 For this Pattern I made up my mind that I should think like an Indian Lady.  Let us consider a family bussiness in a street of Bombay,as it started as a small saree shop 20 years ago.  The bussiness got boomed since then ,so that now they are the owner of small enterprice and they have shops from this end  to the other end of that street. One corner  they have saree shops of various types of sarees like silk, nylon,polyester, cotten etc. On the other corner they have shops they sell matching falls, matching blouse, matching skirts,matching slippers, matching necklace and earings, matching bangles and at last matching Bindi(to put on the forehead); Once you buy a saree from them that is it, they will take you  to other shops to get all the matching items and you can then pay the bill at the end. (It is a family bussiness). 
Now we can  consider "WearableProducts" as a abstract class. All  sareePoducts such as "NylonSarees","SilkSarees " .... are thier concreate implementations.  There is an abstrct class "MatchingProducts"  class extands "WearableProducts"  is our decorator which takes a WearableProduct in its constructor.        
Here is our Component class(WearableProducts)
public abstract class WearableProducts{
string itemName = "";
public String getItemName (){
return itemName();
}
public abstrct double getPrice();
public abstract  void createBill();
public abstract Color getColor();
public abstract void setColor(Color color);
//more methods if you want to
}
This is our decorator class:
public abstract class MatchingProducts extends WearableProducts{
   public abstract String getItemName();
   public abstract boolean findMaching();
//more methods if you want to
}
concreate implemetation of WearableProducts:
public class NylonSarees extends WearableProducts{
Color color;
 public NylonSarees (){
     itemName = "nylon saree";
     
}
public double getPrice(){
return 400.00;
}
   public Color getColor(){
       return color;
}
public  void createBill(){
 System.out.println( " "+getItemName()+" "+getPrice());
}
public void setColor(Color color){
this.color = color;
}
}
My contreate decorator:-
public class  BlouseMatchers extends MatchingProducts{
WearableProduct saree;
String itemName;
Color color;
//define an array of colors;
public BlowseMatchers(WearableProducts saree){
this.saree = saree;
}
public boolean findMatching(){
//gothrough the array of colors
if(a[i] == saree.getColor()){
this.setColor((Color)a[i]);
}
return true;
else
return false;
}
public string getItemName(){
return itemName;
}
public double getPrice(){
  return(saree.getPrice()+100.00);
}
public void ceateBill(){
    saree.createBill();
     System.out.print(" "+getItemName()+" "100.00");
     System.out.Println(" "+getPrice());
}
   public Color getColor(){
       return color;
}
public void setColor(Color color){
this.color = color;
}

}
You can create more decorators like this. FallMatchers,BangleMatchers,NecklaceMatchers .....And you can create SilkSarees,CottonSarees are WearableProduct concreate classes.
while testing
WearableProduct saree = new NylonSarees();
MatchinProducts blouse = new BlouseMatchers(saree);
if (blouse.findMatching()) &&(shoppingisOver)

blouse.createBill();
else ...... you are allowed to go to further decorative stores wrap it with decorators.
MatchingProducts bangles = new BangleMatchers(blouse); (do this only if you get the matching blouse)
MatchingProducts slipper = new SlipperMatchers(bangles);
.......
bindi. createBill(); (this method calls others like recursive method, don't you think it is very powerful?)

I hope I did not confuse Indian Women.

Title:

How To explain "Decorator Pattern" for Indian Women.


Thursday, 9 January 2014

How to....

As I have decided to take a break from writing codes, time for some reading.  I am always interested in object oriented designs, I went back and started to study design patterns again. While I am reading I always make sure that I understand it properly so that I can make it easy for remember as I come back again. This time I started to forget what I have read before, so I thought I am going to write it in a blog so that I can quickly go through if I wanted to. In this blog I will write about Adapter pattern in OO design Patterns.
Adapter Pattern: “Converts the interface of a class into another interface clients expect. Lets classes work together that couldn’t otherwise because of incompatible interface.”
Let us try in a way that we should remember this patterns when we hear the name.
Say, I bought a computer from US but it only works with the American Socket. Here the plug and a computer is our client only understands AmericanSocket Interface. But I have a EuropeanSocket Interface. I build a EuropeanAdapter which takes a EuropeanSocket object.

       public interface AmericanSocket {

               public void optTwoPins();

               public void setPower();

    }

        public class kitchenSocket implements AmericanSocket {

         public void optTwoPins(){

            System.out.println(“I can opt for two pins”);

    }

          public void setPower(){

            System.out.println(“I can work with 120Volts ”);

     }

    }

Now here is EuropeanSocket

   public interface EuropeanSocket {

               public void optThreePins();

               public void setPower();

    }

        public class studySocket implements EuropeanSocket {

         public void setThreePins(){

            System.out.println(“I can opt for three pins ”);

    }

          public void setPower(){

            System.out.println(“I can work with 240Volts ”);

     }

    }

Here is the adapter:

public class EuropeanAdapter implements AmericanSocket{

    EuropeanSocket socket;

    public EuropeanAdapter(EuropeanSocket socket){

     this.socket = socket;

}

public void optTwoPins(){

socket.optThreePins();

}

public void setPower(){

// use a transformer to step down the power.

socket.setPower();

}

}

Now test it

public class AmericanComputer {

    public static void main(String[] args){

        EuropeanSocket socket = new StudySocket();

         AmericanSocket americansocket = new EuropeanAdapter(socket);

          americansocket.optTwoPins();

         americansocket.setPower();

}

}

My computer works now. My computer plug sees adapter as a American Socket.
Title always at the End.

How to remember Adapter Pattern