Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Engineering Concepts (http://www.go4expert.com/articles/engineering-concepts-tutorials/)
-   -   Design Pattern in Simple Examples (http://www.go4expert.com/articles/design-pattern-simple-examples-t5127/)

shabbir 5Jul2007 22:00

Design Pattern in Simple Examples
 
1 Attachment(s)
Instead of defining what is design pattern lets define what we mean by design and what we mean by pattern. According to me design is blue print or sketch of something so it can be defined as creation of something in mind. Moving to pattern, we can define it as guideline, or something that repeats. Now the definition of design pattern becomes creating something in mind that repeats or in other words capturing design ideas as a "pattern" to the problems.

Some problem patterns happen over and over again in a given context and Design Pattern provides a core of the solution in such a way that you can use the core solution every time but implementation should and may vary and the main reason behind that is we have the core solution and not the exact solution. We can discuss an example here about database normalization. Normalization is a pattern (Core solution to database design) but what level of normalization you need (exact solution) depends on your requirement and context.

In this article I will be discussing the following Design patterns ( or common problems and there common solutions which are time tested and have worked when applied ). I will not be defining the design patterns because you can always find them in any standard book but I will be dealing with the actual use and examples of them. To understand the article in a better I would suggest you first download the demo project. To see any sample you make the project as the StartUp project and compile the project and execute it. The solution is build using Microsoft Visual Studio 2005. I have purposely used the abstract classes over interface so the class diagram of the samples looks exactly similar to one suggested by gang of four. If you find a class whose Name is IClassName please don't get upset but its done purposefully to make the class diagrams. In the article I have tried to use as many pictures as possible because "A picture is worth a thousand words"

Creational Patterns

Abstract Factory

- Do we need to create families of objects.

Factory method takes care of one product where as the abstract factory Pattern provides a way to encapsulate a family of products.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...ct-Factory.png

Example

We have a requirement where we need to create control library and the same library supports multiple platforms but the client code should not be changed if we import from one operating system to the other. The solution is

http://imgs.g4estatic.com/design-pattern/AbFactory.png

The client uses the GuiFactory to get the required factory of the supported operating system and calls the same Show Method. Now depending on the platform we change the factory but the client implementation remains the same. If support for new operating system is to be added we need the new factory and the exact implementation of the buttons and without changing the existing code we can support the new platform.

Builder

- Do we need to create object in several steps.

Builds a class based on requirements where Director asks the builder to build each of the parts. Mainly the builder pattern is not used independently but other patterns may have builder pattern as a part where they create the complicated objects using the builder.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...of/Builder.png

Example

http://imgs.g4estatic.com/design-pattern/Builder.png

Who is what?

Waiter is Director
PizzaBuilder is Builder
CheesePizzaBuilder and MixedPizzaBuilder are Concretebuilder
Pizza is product

When Waiter (Director) is asked to serve it creates the Pizza (Product) using the PizzaBuilder.

Another example could be Maze which is a complicated object build from walls and rooms.

Factory

- Do we need to have derived classes figure out what to instantiate and decouple client from instantiated class.

Client uses the factory to create products and its the factory which decides when the actual product is needed for instantiation. This way client decouples the instance and can be saved from some of the crucial operations of object copy if the type of object may change after creation.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...of/Factory.png

Example

http://imgs.g4estatic.com/design-pattern/Factory.png

Who is what?

ComputerFactory (Creator)
ConcreteComputerFactory (ConcreteCreator)
Processor (Product)
ConcreteProcessor (ConcreteProduct)

When the GetProcessor of ComputerFactory is called its the ConcreteComputerFactory creates the ConcreteProcessor and the creation of ConcreteProcessor is delayed till we call the GetProcessor() function.

Another good example could be logging, where we create the instance of the logger factory but instantiate the logger class when actual logging is done.

Prototype

- Do we have too many classes to instantiate / or is the object creation a cumbersome process.

Mainly we don't create the objects of a class directly but clone the existing object and change the state of the object as needed. The main application of such pattern is when the object creation is costly. As an example we have a database class the constructor sets up the database for the class. Now for each new user logging to the system once the system is up we don't setup the database but just clone the first object and change the user specific details like user name / password to validate the user.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat.../Prototype.png

Example

http://imgs.g4estatic.com/design-pattern/Prototype.png

I would not explain here who is what because its pretty much evident.

Singleton

- Do we need to limit the no of objects of a class.

Ensures only one (n = 1..n) instance. The pattern explains how you can achieve the singleton class. It says to have the constructor as private and have a static method to access the instance of the class using that method.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat.../Singleton.png

Example

http://imgs.g4estatic.com/design-pattern/Singleton.png

I would not explain here who is what because its pretty much evident.

Structural Patterns

Adapter

- Do we have the right stuff but wrong interface.

We use the adapter design pattern where the requirements is to convert between one interface to another. Adapter pattern is never implemented when designing a new system but with the changing requirements we have deferring interfaces then adapter comes into picture.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...of/Adapter.png

Example

We have used some library where we have Add function which takes two integer and provides the sum of them. Now when upgrading the libray we find that the library has changed the Add function such that it takes 2 floating point number. Now one option could be to change all the client code where we have used the Add method or other option is to have an Adapter.

http://imgs.g4estatic.com/design-pattern/Adapter.png

CalcAdapter calls the necessary library function after making the necessary changes (in our example conversion between the data types)

Bridge

- Do we have one variation using another variation in a varying way.

Decouple an abstraction from its implementation so that two can vary independently. In strategy pattern we decouple the behavior but in Bridge we decouple the abstraction.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pattern/gof/Bridge.png

Example

In Abstract Factory we discussed about the problem of creating a control library for various operating system. Now creating the library from the scratch is never a good idea and so we may need to use some of the existing infrastructure or library available. We may use the XWindow toolkit or MacWindow toolkit as the base depending on the user platform and toolkit available.

The DrawRect actually uses the DrawLine function which actually is dependent on the type of implementation and we seperate the implementation from the abstraction and have a link ( or bridge ) between the two.

http://imgs.g4estatic.com/design-pattern/Bridge.png

Composite

- Do we have units and groups and want to treat them the same way.

Compose the objects in a tree structure where individual objects as well as the composed objects behave uniformly. Composed objects delegates the requests to the individual leaf objects.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat.../Composite.png

Example

We have some simple graphics and have some graphics which are composed of these simple graphics and as a client both should behave uniformly.

http://imgs.g4estatic.com/design-pattern/Composite.png

Folder browsing could be other example where from the client's point of view its an operation on the folder tree irrespective of its folder ( composite object ) or file ( leaf object ).

Decorator

- Do we need multiple additional functions we may need to apply, but which and how many we add varies, without sub classing.

Attach additional responsibilities to an object dynamically. It has the capability of performing some additional operations before or after the basic operation.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat.../Decorator.png

Example

Say we have a FileReader class where the file can be read based on the combination of applying any of the formulas like it could be
  • Zipped.
  • Encrypted.
  • Zipped and encrypted.
  • encrypted then zipped and ecrypted again.

The solution is Decorator pattern where we apply the options based on the requirement.

Code: CSharp
FileReader file = new FileReader();
// Zip the File
ZipReader zip = new ZipReader(file);
// Encrypt the zip file
EncryptedReader enc = new EncryptedReader(zip);

enc.Read();

Code: CSharp
FileReader file = new FileReader();
// Encrypt the file
enc = new EncryptedReader(file);
// Zip the encrypted file
zip = new ZipReader(enc);

zip.Read();

We can apply any combination as and when needed and also new methods of encryption is very simple. Just add the new class as sibling of EncryptedReader

http://imgs.g4estatic.com/design-pattern/Decorator.png

Facade

- Do we want simplify, beautify or OO-fy an existing class or subsystem.

When client is decoupled from the system using an inter mediator its called facade. Facade behaves as a door to subsystem and provides a single interface to complex interface in the subsystem. Here a point to note is that the subsystem should not have a dependency on the FACADE and if thats the case then the facade is a part of the sub-system and it should move into the sub-system and we should have a new facade class.

Also Facade is not the only entry point to the sub-system but is a convenient point of communication to the subsystem and client can always have the direct access to the subsystem.

This methods helps in developing the subsystem independently without affecting the clients using them.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pattern/gof/Facade.png

Example

We have a Car System creation where the car is created based on the complex subsystems like wheel, steering, chassis, body ...

http://imgs.g4estatic.com/design-pattern/Facade.png

Flyweight

- Do we have too many part objects.

Any objects state can be classified into two types of data that it can store one is intrinsic (static and independent of object) and one is extrinsic (non-static and depend on the state of the object) then flyweight pattern can be applied. The design pattern is useful when we have large no of objects which can be grouped once the extrinsic state is removed and it uses de-encapsulation to split the objects.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat.../Flyweight.png

Example

We have some shape objects and the shape objects are really costly and so we can have the shape object split itself such that some data which is independent of the state of the object is kept in the object and other data is provided externally. Say in our shape object how the shape is drawn is same but where the shape is drawn is dependent on the state of the object and so the print method should know where to print which is extrinsic and should be supplied.

http://imgs.g4estatic.com/design-pattern/Flyweight.png

Proxy

- Do we need to optionally add some new functionality to something that already exists. Do we need to control how an object is accessed.

It provides a placeholder for another objects and the proxy object gives the impression to the client that actual request is handled by the proxy but it just delegates the request to the real subject.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pattern/gof/Proxy.png

Example

Say we have a system setup where we send and receive data over the network. Now due to some security reasons data are encrypted and so now they need to be decrypted before processing and so now we are in trouble because all the client code needs to be changed to decrypt the data or we may need to change the stable library code which use to send/recieve the data. Now the solution could be to have the proxy which will do the additional responsibility given to the system and then send the data using the well tested system in place.

http://imgs.g4estatic.com/design-pattern/Proxy.png

We should be using the proxy system where we think we may need to add some additional responsibilities later.

Behavioral Patterns

Chain of Responsibility

- Do we have diff. objects that can do the job but we do not want the client object know which is actually going to do it.

Avoid coupling the sender of a request to its reciever by giving more than one object a chance to handle the request. Helps in reducing the coupling though they are chained, but does not know about other objects apart fron the fact that they derive from the common interface.

Best example could be Context help where the each help component tries to perform the request and when fail they pass the request in the chain to other members.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...onsibility.png

Example

In the banking system where cheque's for clearing is approved by the person but if the cheque amount is beyond certain limit, the approving responsibility moves the person higher in authority in the bank.

Windows messaging system works in the similar method where the messages are processed by the controls if the point likes with the bounds of the control or goes to the parent.

http://imgs.g4estatic.com/design-pat...hainOfResp.png

Command

- Do we need to decouple request from handler.

Encapsulate requests for service from an object inside other object(s) and manipulate requests. Command objects are mainly helpful in undo/redo operation where the previous state can be saved for reloading or even the necessary command(s) can be stored in stack for the same.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...of/Command.png

Example

Say we have designed an image editor and user can have the option of opening file from various ways like menu, tool bar, double click on a file in the explorer. The solution is the command pattern where the FileOpen command is associated in the viewer itself and when the command executes the file is shown in the viewer.

http://imgs.g4estatic.com/design-pattern/Command.png

The other example could be the operations on the images.

Interpreter



As the name suggest it interpret your expression. Some expressions are atomic and some complex which are made up of atomic and it interprets the atomic and complex expressions uniformly. It mainly uses in the compilers / parsers / Macro expansions.

http://imgs.g4estatic.com/design-pat...nterpreter.png

I have not provided any sample because this one is not that often used just for completeness of the article have mentioned the pattern here.

Iterator

- Do we want to separate collection from client that's using.

Provide a way to access the elements of an aggregate objects sequentially without exposing its representation. We can make the client independent on the movement of the cursors like forward traversal / backward traversal as well as the internal implementation of the list.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...f/Iterator.png

Example

http://imgs.g4estatic.com/design-pattern/Iterator.png

I would not explain here who is what because its pretty much evident and nowadays any modern language supports this and so you could use the foreach loop. In C-Sharp if you would like to have a class that will be a list you need to use the IEnumerator and IEnumerable interfaces and then it will support the foreach loop.

List should implement IEnumerable and the Iterator should implement IEnumerator.

Mediator

- Do we have a lot of coupling in who must talk to whom.

Define objects in the subsystem where the set of objects interact. This pattern is much similar to the Facade but in facade the sub-system knows nothing about the Facade but here the sub-system communicate through the mediator and the client also communicate through the mediator. Mediator hides the complicated communication in the subsystem where as facade sub-system classes are open to the client as well, So Facade is an optional point of communication where as Mediator is only point of communication to the subsystem.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...f/Mediator.png

Example

Now don't blame me if for the third time I take the example of the control library where we have a dialog and some controls over the dialog. The controls can be interacted through the DialogMediator. Now if the siblings of the Dialog would like to interact they do so through the DialogMediator because its the DialogMediator who has the information about the rest of the sub-system

http://imgs.g4estatic.com/design-pattern/Mediator.png

Memento



Delegate some activity to some other class like some helper classes to do the job.

The memento pattern is used to encapsulate the current state of an object in a memento object in order to be able to restore the object state later without exposing the internal representation of the object to the outside world. The memento pattern is useful when you have an object which you would to take a "snapshot" of so that at a later time you could use the snapshot to restore it to its original state, such as an undo or rollback operation.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...of/Memento.png

Example

Suppose you have a an object which stores form information and you would like to allow the user to make changes in the form and then if they make a mistake later you can put back in the original form values. Well, you could serialize the form object and then un-serialize it later but this is obviously messy and not a good solution. Another possible solution would be to have an outside object use the form's accessors methods to pull out what you need to save the state but this causes high coupling between the class saving the state and the form; any changes in the form would require changes in the other class. We need something that will allow you to save the state and restore it later without having to get involved in the details. This is where the memento pattern comes in.

http://imgs.g4estatic.com/design-pattern/memento.png

Observer

- Do various entities need to know about events that have occurred? How to keep dependent object up-to-date.

When we have one to many dependency between objects so when the object changes, its dependents are notified of the update automatically. The best example is something like Excel with data in one cells and we have multiple charts which gets updated when there is change in the data. This design pattern is more useful if we have one sided broadcast communication and is useful when we have one to many relationship.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...f/Observer.png

Example

When any data is changed in the XMLDoc object it calls the Notify Method of the base class which has the list of the active observers attached to the XMLDoc and calls the Update method of all the view of the data.

http://imgs.g4estatic.com/design-pattern/observer.png

State

- Do we have a system with lots of states where keeping track of code for differrent states is difficult.

Allow the object to alter it behavior when its internal state change.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pattern/gof/State.png

Example

We have a Printer system where we have the following states for the printer and based on the actions taken in particular state, the state of the printer changes accordingly.

http://imgs.g4estatic.com/design-pat...ateDiagram.png

Instead of having the state defined in the printer itself we keep the state of the printer into separate object and separate the responsibilities. "Have objects for state."

http://imgs.g4estatic.com/design-pattern/State.png

Strategy

- Do we have a varying rule or algorithm.

Define a family of algorithms, encapsulate each one and make them interchangeable. It allows us to change the algorithm independently with out changing the client using it. It converts the generalization of the template method to composition or aggregation.

It has various uses like it allows the algorithm to vary frequently and is a very good alternate solution to sub-classing.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...f/Strategy.png

Example

We have a payment system where we have an Invoice class where we calculate the total of the amount payable but the requirement is such the amount calculation depends on the type of customer and discount offer. Also over the time the offers / discount may differ and may need to change the offer at run-time. The solution is

http://imgs.g4estatic.com/design-pattern/Strategy.png

Now if have some special offer coming for the season sale all we need to do is add a new class derived from NetPayable and then add the necessary calculation logic in that class and this way we can have the new algorithm added dynamically.

Template Method

- Do we have a skeleton of the algorithm and want to leave upto the sub classes how each step behaves.

Define the skeleton of the algorithm in an operation and deferring the exact implementations of the steps of the algorithms to its subclasses. Template method uses the HR policy of "we will call you" which means the exact implementations of the algorithm will be called by the base class.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...ate-Method.png

Example

Printing algorithm for various types of documents where the algorithm is fixed of printing the header then body and at last the footer which is defined in the base class the exactly how the headers are printed is defined in the supported document classes.

http://imgs.g4estatic.com/design-pattern/Template.png

Visitor

- Do we have new tasks that we will need to apply to our existing classes.

Represent an operation to be performed on the element of an object and helps you add new methods to existing hierarchy without affecting the existing hierarchy. This also de-encapsulate where we break the class so that some future functionality can be added but it has the disadvantage that concrete elements cannot be added without changing the interface. Use of the pattern should be done if you have the concrete elements fixed but you may need to add the new functionality to the existing object.

Typically the class diagram looks like

http://imgs.g4estatic.com/design-pat...of/Visitor.png

Example

We have the number of objects supported in the drawing system fixed but we need to add the depth in the way the object does it operations like scale or drawing of the object. We could have the same class do both the job but we need some specialist in the field doing the job. A mathematician is good at doing the scaling but not at drawing or vice versa and so here we use the visitor pattern.

http://imgs.g4estatic.com/design-pattern/Visitor.png

Accept method actually calls the correct implementation based on the visitor passed, so its the client who tells if he needs to draw or scale.

GOLDEN RULE(s) of design pattern
  1. Client should always call the abstraction (interface) and not the exact implementation.
  2. Future changes should not impact the existing system.
  3. Change always what is changing.
  4. Have loose coupling
    • Inheritance ( Very coupled )
    • Composition
    • Aggregation
    • Association
    • Dependency
    • Realization ( Least couple )

asadullah.ansari 6Mar2008 10:37

Re: Design pattern in simple examples
 
Shabbir excellent. Thanks a lot . I had a little bit confusion on state design pattern.

shabbir 6Mar2008 11:26

Re: Design pattern in simple examples
 
Quote:

Originally Posted by asadullah.ansari
Shabbir excellent. Thanks a lot . I had a little bit confusion on state design pattern.

My pleasure

ngungo 4Apr2008 23:58

Re: Design pattern in simple examples
 
This is my first post. I try to convert the Abstract Factory class in c# to php. Of course, it does not work. Can you correct it for me, or give me a hint. Thanks.
--ngungo

Code:

<?php
  class GUIFactory {
      function GetFactory() {
                        if (TRUE) return new MacFactory();
                        else return new WinFactory();
      }
      public function CreateButton() {};
      public function CreateLabel() {};
  }

  class WinFactory extends GUIFactory {
      // Its there just to have the Classdiagram going
      $btn = new WinButton();
      $lbl = new WinLabel();
      public override function CreateButton() {
        return $btn;
      }

      public override function CreateLabel() {
        return $lbl;
      }
  }

  class MacFactory function GUIFactory {
      // Its there just to have the Classdiagram going
      $btn = new MacButton();
      $lbl = new MacLabel();
      public override function CreateButton() {
        return $btn;
      }

      public override function CreateLabel() {
        return $lbl;
      }
  }

  abstract class Control {
      public abstract function Show();
  }

  class WinButton extends Control {
      public override function Show() {
        echo "I'm a WinButton: ";
      }
  }

  class MacButton extends Control {
      public override function Show() {
        echo "I'm an MacButton: ";
      }
  }

  class WinLabel extends Control {
      public override function Show() {
        echo "I'm a WinLabel: ";
      }
  }

  class MacLabel extends Control {
      public override function Show() {
        echo "I'm an MacLabel: ";
      }
  }
 
        $factory = GUIFactory.GetFactory();
        $button = factory.CreateButton();
        echo $button->Show();
       
        $label = factory.CreateLabel();
        echo $label->Show();
?>


shabbir 7Apr2008 11:51

Re: Design pattern in simple examples
 
I don't see any error in code. Can you please explain what problem you are facing.

ixcafe 12Apr2008 01:09

Re: Design pattern in simple examples
 
Nice condensed in a nutshell introduction of DP.

Did you write this article yourself?

Which flowchart software you used? They look nice!!!

Way to go

shabbir 13Apr2008 10:49

Re: Design pattern in simple examples
 
Thanks and yes I have written the article myself and I have used couple of softwares. One is EA and other is the class diagram provided in Visual studio 2005

ryms 18Jun2008 14:50

Re: Design pattern in simple examples
 
thank you very much for this works!!!

superdat 4Jul2008 14:32

Re: Design pattern in simple examples
 
Nice post! Thank you very much!

Dean-123 18Jul2008 13:22

Re: Design pattern in simple examples
 
which do you think is most important when design a website?
i recently designed a new website:mytino(you can search it by google)can you give me some advices?
thank you!

shabbir 18Jul2008 14:04

Re: Design pattern in simple examples
 
Quote:

Originally Posted by Dean-123
which do you think is most important when design a website?
i recently designed a new website:mytino(you can search it by google)can you give me some advices?
thank you!

Hey thats a too general thing to answer and it would be a classic case of solution probleming where you have a solution and trying to find the problem where it can be applied. I would suggest get your context out and then see which is the most fitting situation and see if you really need it and then apply.

Dean-123 21Jul2008 06:48

Re: Design pattern in simple examples
 
Quote:

Originally Posted by shabbir
Hey thats a too general thing to answer and it would be a classic case of solution probleming where you have a solution and trying to find the problem where it can be applied. I would suggest get your context out and then see which is the most fitting situation and see if you really need it and then apply.

thank you for your kindly suggestion,it's really useful!

ziad 23Jul2008 17:42

Re: Design pattern in simple examples
 
Shabbir great article, thanks very much!

I have a question regarding the strategy pattern. I think I understand it correctly and see the benefit of using it but my question is how will the correct implementation of the interface be instantiated? Would you have to use one of the creational design patterns?

Thanks again.

Ziad

yah 12Sep2008 07:29

Re: Design pattern in simple examples
 
hai..
i'm new in Design pattern using Java..
actually i try to find any topic in design pattern to my PHD..
any suggestion from you?
TQ

rmahmood 18Sep2008 13:33

Re: Design pattern in simple examples
 
Nice article with very simple examples. :)

It would be nice if you can share your knowledge to help me out.

I am working on an application where i have recorded ejb method calls with necessary information in XML files as they were called by j2ee client. Now i want to replay these recorded methods using Java reflection.

I am thinking about some design pattern that can be helpful. Important thing for me is
for every method being replayed i have to call ProcessBefore and ProcessAfter methods
to fix some contextual issues if there exist. It is not possible for me to know in advance
which methods will be recorded so that i can write concrete ProcessAfter and ProcessBefore for them.

Nikimathew 25Sep2008 10:13

Re: Design pattern in simple examples
 
Design pattern is a widely accepted solution to a recurring design problem in OOP a design pattern describes how to structure classes to meet a given requirement provides a general blueprint to follow when implementing part of a program does not describe how to structure the entire application does not describe specific algorithms focuses on relationships between classes
----------------
Nikimathew

puviyarasan 10Dec2008 11:36

Re: Design pattern in simple examples
 
It is really good article. Thank you very much.:)

annant 15Dec2008 16:47

Some Real world example with database
 
Can you pls provide me any good example of Abstract Factory pattern used in a project within database interaction. For example a project in Abstract factory pattern, which also has some database associated with it .

sanc.pec 1Jan2009 05:33

Re: Design pattern in simple examples
 
Hi ,
It was a superb collection of DPs.. Really very good man.
I ahve one scenario in my project, like the project is now on LIVE. A sudden requiremnt from customer requires some 400 different objects to behave in a single way. Like he needs a single object called "DOCUMENT" for all those 400 objects !! :crazy:

Object 1 ->
attr A
attr B

Object 2->
attr C
attr D

Now my DOCUMENT generic object should have
attr A
attr B

when he wants Object1

and similarly for Object 2 and other objects !!! What can be done ?????

shabbir 1Jan2009 10:11

Re: Design pattern in simple examples
 
Confused. Is there 2 type of object or one and if 2 type of object like to behave like one then you could probably change the class 2 to have internal implementation taken from object 1.

sanc.pec 2Jan2009 21:24

Re: Design pattern in simple examples
 
Hi shabir,
I cannot change any implementations in the existing classes [as i already said they are in LIVE !!].
The scenario for me is like this..

OBJECT1
ATTR1
ATTR2
LIST<OBJECT2> [it may also have list of objects like this]

OBJECT2
ATTR3
ATTR4

I need a generic class called
OBJECT3
Where it should have only attributes of OBJECT1 , when i initialise OBJECT3 with some requirments. I can just go with Fatory creation pattern, but the problem is how to create this object automatically and how to make my code to access only ATTR1 & ATTR2 & List<OBJECT2> when i need my OBJECT3 to act as OBJECT1.

Am i clear ? :baby:

shabbir 4Jan2009 03:29

Re: Design pattern in simple examples
 
As I can think you cannot apply it in the mid of something but yes you should not touch the existing code and so best form can be to use some creational pattern to create the needed object and give the object to the accessible methods.

shae marks 24May2009 21:25

Re: Design pattern in simple examples
 
An element of a page, for instance a title, is shown as it would normally appear viewing the page without admin rights. However, once the logged in user has his mouse over the element, its background color is highlighted and a tooltip is shown prompting the user to click the element to edit it. Once the user clicks the element, it is transformed into an input field (text, dropdown, etc.) as well as a save button and a cancel button. Often, the input field matches the styling of the original element. So that if the original element was a header written in size 20pt, the size of the font in the input field would also be 20pt. This styling is made to ensure that the user can connect the original element with the new replaced editable element.
The user can then edit the value of the input field (which is the same as the original elements value) and click save or cancel. If ‘save’ is clicked, the value is saved through and AJAX call to the underlying database, and the view of the element is changed back to the original (for instance the header without the edit input field), but now with the new value. If cancel is clicked, the view element is changed back to the original without any changes that might have been written in the edit input field.
This pattern is often combined with an the AJAX technique, which is an asynchronous call to the server through javascript, that does not require a refresh of the page. There are many javascript libraries out there, that delivers ready-to-use inplace editors.
Rationale

An in-place editor provides an easy way to let the user edit parts of a page without having to be redirected to an edit page. Instead, the user can just click around on a page an edit the elements he or she wishes to change – without reloading the page.
The pattern is often associated with web 2.0 websites.

shobhaaradhya 3Jun2009 14:51

Re: Design pattern in simple examples
 
Hi Shabbir,

Excellent article. I found the article very usefull. I was struggling to understand the design pattern concepts. You have explained in a simple and understandable way also with examples.

Thanks a lot.

Regards,
Shobha

shabbir 3Jun2009 20:30

Re: Design pattern in simple examples
 
The pleasure is all mine.

binclintonusa 13Jun2009 08:42

Re: Design pattern in simple examples
 
Thank you very much for the lesson. I knew that I can do this in better way.

WaibelRD 1Sep2009 05:23

Re: Design pattern in simple examples
 
Outstanding!

I think I have been doing this for years but never realized there were "names" and "functionality" associated with what I was doing.

Great Job and THANK YOU!

Rob Waibel

shabbir 1Sep2009 09:04

Re: Design pattern in simple examples
 
Thats the beauty of Design Pattern and we use them more often without actually knowing them

tsnany115 5Sep2009 09:01

Re: Design pattern in simple examples
 
Hi all, I am a new member of forum

praba_expert 22Sep2009 14:11

Re: Design pattern in simple examples
 
good work shabbir:nice:

shabbir 22Sep2009 22:36

Re: Design pattern in simple examples
 
The pleasure is all mine

bharathi_rg@yahoo.co 4Dec2009 09:58

Re: Design pattern in simple examples
 
simple and easy understand !!

Rajneeshgarg 14Dec2009 13:46

Re: Design pattern in simple examples
 
Thanks shabbir, From where i can get these examples in C++, actually i have no knowledge of java. please inform ASAP.

shabbir 14Dec2009 15:04

Re: Design pattern in simple examples
 
Quote:

Originally Posted by Rajneeshgarg (Post 61654)
Thanks shabbir, From where i can get these examples in C++, actually i have no knowledge of java. please inform ASAP.

I have them in C# and not in Java and language is pretty simple and examples also does not take much of C# into account. I am also not an expert at C# BTW

mmagdy 1Jan2010 00:47

Re: Design pattern in simple examples
 
thank you ,this is really very helfull:)

jameschowdary 13Feb2010 00:19

Re: Design pattern in simple examples
 
A sample of 2 methods implement 3 tier or entire applying design patterns
that will helpful to understand

nosizejosh 30Mar2010 21:25

Re: Design pattern in simple examples
 
thanks man! i am a beginner programmer and i think i im more comfortable with java, currently learning design patterns and i stumbled upon this article, it is really helpful so thanks a lot.

anyway i have a project to design and implement a memory game using java and im wondering if any of these patterns can be helpful in my design

thank you all!

elhassane 31Mar2010 05:50

Re: Design pattern in simple examples
 
thnx friend for your lesson it's very very interessent

mvmmk78 27May2010 13:10

Re: Design pattern in simple examples
 
Hi This is Murali. I downloaded the DesignPatternCodeSample.zip . and I am trying to open the project using VC 2005 editor. I am not able to open the project. Inside the folder there is only one file without any Ext (file name : DesignPatternCodeSample). Could you please help me or mail me those sample project if possible. My Email id is mvmmk78@gmail.com

shabbir 27May2010 15:01

Re: Design pattern in simple examples
 
Download it once again because there are many files in the zip file


All times are GMT +5.5. The time now is 00:05.