Showing posts with label Object Oriented. Show all posts
Showing posts with label Object Oriented. Show all posts

Saturday, June 4, 2016

design pattern

I read an article Design Patterns Are Not Blueprints. I like author's opinion.

"A pattern is a way of thinking about something and a way of communicating about something. To follow the example implementation of a pattern without thinking is as silly as doing anything else without thinking."

We should not use a design pattern just because it is design pattern. We need understand what problem the design pattern solves or in which scenario we shall use the design pattern.

Design pattern is to make complicated things to simple ones.

To me, the principle of coding is

  • easy to read
  • easy to maintain
  • easy to extend

Technique? What I follow is Tao – beyond all techniques!

Thursday, December 5, 2013

23 Gang of Four Design Patterns

Creational Patterns
  1. Abstract Factory:  Creates an instance of several families of classes, the factory. Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
  2. Builder: Separates object construction from its representation. Separate the construction of a complex object from its representation so that the same construction processes can create different representations.
    • The intention of builder is to avoid a huge list of constructor. For example
      We have a Car class. The problem is that a car has many options. The combination of each option would lead to a huge list of constructors for this class.
      class Car is
        Can have GPS, trip computer and various numbers of seats. Can be a city car, a sports car, or a cabriolet.
      class CarBuilder is
        method getResult() is
            output:  a Car with the right options
          Construct and return the car.
        method setSeats(number)
        method setCityCar()
        method setCabriolet() is
        method setSportsCar() is
        method setTripComputer() is
        method unsetTripComputer() is
        method setGPS() is
        method unsetGPS() is
        …
      Construct a CarBuilder called carBuilder
      carBuilder.setSeats(2)
      carBuilder.setSportsCar()
      carBuilder.setTripComputer()
      carBuilder.unsetGPS()
      car := carBuilder.getResult()

      Another example here, to make a meal

  3. Factory Method: Creates an instance of several derived classes. Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. an example of polymorphism
  4. Prototype: A fully initialized instance to be copied or cloned. Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  5. Singleton: A class of which only a single instance can exist. Ensure a class only has one instance, and provide a global point of access to it.
Structural Patterns
  1. Adapter: Match interfaces of different classes.Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
  2. Bridge: Separates an object’s interface from its implementation. Decouple an abstraction from its implementation so that the two can vary independently.
    • JDBC-ODBC Bridge
      another example
      interface Engine
          method go
      abstract class Vehicle
          constructor Vehicle(engine)
          method drive() { engine.go();}
      Two classes implemented Engine
          NormalEngine
          RacingCarEngine
      Two solid classes extend Vehicle
          CivilCar
          RacingCar
      Vehicle car = new CivilCar(new NormalEngine());
      car.drive() –> actually it is alling normalEngine.go()
      The implementation is on normalEngine, decoupled from vehicle.
  3. Composite: A tree structure of simple and composite objects. Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
  4. Decorator: Add responsibilities to objects dynamically.  Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
  5. Facade: A single class that represents an entire subsystem. Provide a unified interface to a set of interfaces in a system. Facade defines a higher-level interface that makes the subsystem easier to use.
  6. Flyweight: A fine-grained instance used for efficient sharing. Use sharing to support large numbers of fine-grained objects efficiently. A flyweight is a shared object that can be used in multiple contexts simultaneously. The flyweight acts as an independent object in each context — it’s indistinguishable from an instance of the object that’s not shared.  Here is the code example https://sourcemaking.com/design_patterns/flyweight/java/1. When the factory is asked for an instance, it is checking if the instance is created before. If yes, return the instance otherwise create the instance and keep the reference. The instance here shall be immutable as it is shared. It is like a cache. 
    • java.lang.Integer#valueOf(int) (also on Boolean, Byte, Character, Short, Long, Float and Double)
    • Java String creation. (Read about string creation in Java specification)
    • Swing borders
  7. Proxy: An object representing another object. Provide a surrogate or placeholder for another object to control access to it.
    • Spring AOP creates proxies for supplied objects
    • java.lang.reflect.Proxy
    • java.rmi.*, the whole API actually.
    • proxy vs decoration: proxy controls on the method call of the target class; while decoration adds more functions on the target class
Behavioral Patterns
  1. Chain of Resp. : A way of passing a request between a chain of objects. Avoid coupling the sender of a request to its receiver by giving more than one object a  chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
  2. Command: Encapsulate a command request as an object. Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.  
  3. Interpreter: A way to include language elements in a program. Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. (recognizeable by behavioral methods returning a structurally different instance/type of the given instance/type; note that parsing/formatting is not part of the pattern, determining the pattern and how to apply it is)  //TODO
  4. Iterator: Sequentially access the elements of a collection. Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
  5. Mediator: Defines simplified communication between classes. Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.  http://javapapers.com/design-patterns/mediator-design-pattern/
  6. Memento: Capture and restore an object's internal state. Without violating encapsulation, capture and externalize an object’s internal state so that the object can be restored to this state later. Memento pattern is implemented with two objects – Originator and Caretaker. The originator is some object that has an internal state. The caretaker is going to let the originator save the state or restore the saved state.
  7. Observer: A way of notifying change to a number of classes. Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
  8. State: Alter an object's behavior when its state changes. Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. 
    • javax.faces.lifecycle.LifeCycle#execute() (controlled by FacesServlet, the behaviour is dependent on current phase (state) of JSF lifecycle)
    • example, an order, state new –> placed –> shipped –> finished –> returned and cancelled. For each status, the behavior is different. For example, an order which is new or placed can be cancelled, but cannot be returned; an order which is shipped or finished cannot be cancelled, the finished order can be returned, nothing shall be done on an cancelled order.
  9. Strategy: Encapsulates an algorithm inside a class. Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Make an algorithm's behaviour can be selected at runtime
  10. Template: Defer the exact steps of an algorithm to a subclass. Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. (recognizeable by behavioral methods which already have a "default" behaviour definied by an abstract type)
  11. Visitor: Defines a new operation to a class without change. Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. The pattern should be used when you have distinct and unrelated operations to perform across a structure of objects. This avoids adding in code throughout your object structure that is better kept separate.

Monday, June 27, 2011

Cohesion and Coupling

■ Cohesion measures how closely aligned a module’s classes are with each other and with achieving the module’s intended functionality. You should strive for high cohesion in your modules. For example, a module shouldn’t address many different concerns (network communication, persistence, XML parsing, and soon): it should focus on a single concern.  In a nutshell, cohesion means single function.


■ Coupling, on the other hand, refers to how tightly bound or dependent different modules are on each other. You should strive for low coupling among your modules. For example, you don’t want every module to depend on all other modules.

Wednesday, November 19, 2008

Disadvantage of loose coupling

Loosely coupled systems can make it difficult to understand the "big picture" of the solution—the overall flow of messages through the system. This is a common problem with messaging solutions, and the use of routers can exacerbate the problem. If everything is loosely coupled to everything else, it becomes impossible to understand in which direction messages actually flow. This can complicate testing, debugging, and maintenance.

Monday, July 28, 2008

The Liskov Substitution Principle (LSP)

Subtypes must be substitutable for their base types. It must make sense for "is-a" testing. For example, sedan IS A car, which makes sense, so sedan is substitutable for car.

Inheritance (and the LSP) indicate that any method on base class should be able to used on the sub types. For example, car has a method called startEngine(), which also makes sense to let sedan have this method.

Delegation
If you need to use functionality in another class, but you don't want to change that functionality, consider using delegation instead of inheritance.

Composition
You can use composition to assemble behaviors from other classes. Here is one example:

Suppose we wanted to develop a Weapon interface, and then create several implementations of that interface that all behave differently. Now we need to use the behaviour in our Unit Class. But we don't want to tie to a specific implementation of Weapon. Composition is most powerful when you want to use behavior defined in an interface, and then choose from a variety of implementations of that interface, at both compile time and run time. Pizza is actually a great example of composition. It is composed of different ingredients, but you can swap out different ingredients without affecting the overall pizza slice.
When an object is composed of other objects, and the owning object is destroyed, the objects that are part of the composition go away, too. The behaviors in a composition do not exist outside of the composition itself.

Aggregation
When you want the benefits of composition, but you are using behavior form an object that does not exist outside your object, use aggregation

If you favor delegation composition, and aggregation over inheritance, your software will usually be more flexible, and easier to maintain, extend and reuse.

The LSP is about when to subclass. If your subclass really is substitutable for its base type, then use inheritance. If not, then you might look at other OO solutions like delegation, composition or aggregation.

Friday, July 18, 2008

The Single Responsibility Principle (SRP)

Every object in your system should have a single responsibility, and all the object's services should be focused on carrying out that single responsibility.

THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE.

Cohesion is another name for the SRP. The SRP will often make you classes bigger. Since you're not spreading out functionality over a lot of classes, you're putting more things into a class.

This is the reason why many people separate their applications into layers, for example, the data access layer, the business layer and the presentation layer. Hopefully a change in one layer won't cause a ripple effect of changes in other layers, or at least, keep the impact to a minimum. A popular example that "violates" this principle is placing persistence logic in your business classes. By doing so, you have 2 reasons for a business class to change. First, when you need to change the persistence logic, and second, when you need to change the business rules.

Most of the time, you can spot classes that aren't using the SRP with a simple test:

For example,

Read each line below, if what you read does not make sense, you're probably violating the SRP with that method. That method might belong to a different class.

Once you've done an analysis, you can take all the methods that don't make sene on a class, and move those methods to classes that do make sense for that particular responsibility.

When a method takes parameters, like wash(Automobile) on the CarWash class. You would write "The CarWash washes [an] automobile", which makes sense.

Wednesday, July 16, 2008

The Don't Repeat Yourself (DRY) Principle

Don't Repeat Yourself (DRY)means "Avoid duplicate code by abstracting out things that are common and placing those things in a single location".

DRY is really about ONE requirement in ONE place. The benefit is once the requirement is changed, you only need change codes in ONE place in the whole application.

The Open-Close Principle (OCP)

SOFTWARE ENTITIES (CLASSES, MODULES, FUNCTIONS, ETC.) SHOULD BE OPEN FOR EXTENSION, BUT CLOSED FOR MODIFICATION.[Martin]

OCP is essentially equivalent to the Protected Variation pattern: Identify points of predicted variation and create a stable interface around them.

The Open Close Principle states that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged.

Example
Bellow is an example which violates the Open Close Principle. It implements a graphic editor which handles the drawing of different shapes. It's obviously that it does not follow the Open Close Principle since the GraphicEditor class has to be modified for every new shape class that has to be added. There are several disadvantages:
  • for each new shape added the unit testing of the GraphicEditor should be redone.
  • when a new type of shape is added the time for adding it will be high since the developer who add it should understand the logic of the GraphicEditor.
  • adding a new shape might affect the existing functionality in an undesired way, even if the new shape works perfectly


// Open-Close Principle - Bad example
class GraphicEditor {
public void drawShape(Shape s) {
if (s.m_type == 1)
drawRectangle(s);
else if (s.m_type == 2)
drawCircle(s);
}

public void drawCircle(Circle r) {....}

public void drawRectangle(Rectangle r) {....}
}

class Shape {
int m_type;
}

class Rectangle extends Shape {
Rectangle() {
super.m_type = 1;
}
}

class Circle extends Shape {
Circle() {
super.m_type = 2;
}
}


Bellow is a example which supports the Open Close Principle. In the new design we use abstract draw() method in GraphicEditor for drawing objects, while moving the implementation in the concrete shape objects. Using the Open Close Principle the problems from the previous design are avoided, because GraphicEditor is not changed when a new shape class is added:
  • no unit testing required.
  • no need to understand the source code from GraphicEditor.
  • since the drawing code is moved to the concrete shape classes, it's a reduced risk to affect old functionality when new functionality is added.


//Open-Close Principle - Good example
class GraphicEditor {
public void drawShape(Shape s) {
s.draw();
}
}

class Shape {
abstract void draw();
}

class Rectangle extends Shape {
public void draw() {
// draw the rectangle
}
}


Exempt from here.

Tuesday, March 25, 2008

4 major principles of Object-Oriented Programming

Encapsulation, Data Abstraction, Polymorphism and Inheritence.

Encapsulation
What is encapsulation? Well, in a nutshell, encapsulation is the hiding of data implementation by restricting access to accessors and mutators. First, lets define accessors and mutators:
Accessor An accessor is a method that is used to ask an object about itself. In OOP, these are usually in the form of properties, which have, under normal conditions, a get method, which is an accessor method. However, accessor methods are not restricted to properties and can be any public method that gives information about the state of the object.
Mutator Mutators are public methods that are used to modify the state of an object, while hiding the implementation of exactly how the data gets modified. Mutators are commonly another portion of the property discussed above, except this time its the set method that lets the caller modify the member data behind the scenes.
By hiding the implementation of our Person class, we can make changes to the Person class without the worry that we are going to break other code that is using and calling the Person class for information. If we wanted, we could change the fullName from a String to an array of single characters (FYI, this is what a string object actually is behind the scenes) but they callers would never have to know because we would still return them a single FullName string, but behind the scenes we are dealing with a character array instead of a string object. Its transparent to the rest of the program. This type of data protection and implementation protection is called Encapsulation.

Abstraction
An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of object and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer.
Software developers use abstraction to decompose complex systems into smaller components. In short, data abstraction is nothing more than the implementation of an object that contains the same essential properties and actions.

Inheritance
Rather than duplicate functionality, inheritance allows you to inherit functionality from another class, called a superclass or base class.

Polymorphism
Polymorphism means one name, many forms. Any object that can pass more than one IS-A test can be considered polymorphic.