Showing posts with label Design Pattern. Show all posts
Showing posts with label Design Pattern. Show all posts

Monday, July 7, 2014

Flyweight Pattern in Java


Simple Note

From reference "Flyweight pattern":
flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.


Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/flyweight

Run TestMain.java to test.

Assume you need to calculate lots of sum of a range of Fibonacci Numbers.
There are 2 shared items in FibRangedSum:
1. Calculated results (a Map, with Multiton Pattern)
2. Fibonacci sequence (a List, not Multiton Pattern but still Flyweight Pattern)

References:

Flyweight pattern

Fibonacci number

Sunday, June 15, 2014

Composite Pattern in Java


Simple Note

From reference:
the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/composite

Run TestMain.java to test.

A Calculator probably consists of several child Calculators, you can change mode from parent Calculator then get result as needed.

References:

Composite pattern

Saturday, June 14, 2014

Bridge Pattern in Java


Simple Note

From reference:
The bridge pattern is a design pattern used in software engineering which is meant to "decouple an abstraction from its implementation so that the two can vary independently". The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction. The bridge pattern can also be thought of as two layers of abstraction.

Difference between Bridge Pattern and Adapter Pattern:
See reference.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/bridge

Run TestMain.java to test.

Assume there are several calculator implements interface DesiredCalculator and you access them via a Bridge class rather than access them directly.
Once the API of DesiredCalculator is changed, you just need to update the content within Bridge class, all other parts of your program can stay unchanged.

References:

Bridge pattern

Difference between Bridge pattern and adapter pattern

Monday, June 9, 2014

Adapter Pattern in Java


Simple Note

From reference:
The adapter design pattern is used when you want two different classes with incompatible interfaces to work together. Interfaces may be incompatible but the inner functionality should suit the need. The Adapter pattern allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the clients.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/adapter

Run TestMain.java to test.

Assume you hope all calculators implement the interface DesiredCalculator but the PowerOfTwoCalc didn't, and assume it is provided by 3rd party in a jar.
Now you can use Adapter Pattern to create DesiredPowerOfTwoCalculator that implements DesiredCalculator and let PowerOfTwoCalc do real operation inside rather than rewrite all functions yourself.

Reference:

Adapter pattern

Object Pool Pattern in Java


Simple Note

From reference:
The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a "pool" – rather than allocating and destroying them on demand. A client of the pool will request an object from the pool and perform operations on the returned object. When the client has finished, it returns the object to the pool rather than destroying it; this can be done manually or automatically.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/objectpool

Run TestMain.java to test.

The ThreadPool create and handle WorkingThread to execute Runnable task,
and use Decorator Pattern to wrap Runnable task to restore WorkingThread automatically for reuse.

Reference:

Object pool pattern

Singleton Pattern in Java


Simple Note

From reference:
singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/singleton

Run TestMain.java to test.

There is only one Config instance in whole application.

References:

Singleton pattern

Difference between static class and singleton pattern?

Why use a singleton instead of static methods?

Friday, June 6, 2014

Prototype Pattern in Java


Simple Note

From reference:
The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
* avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
* avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/prototype

Run TestMain.java to test.

There are several default membership packages of a gym and you can always talk to salesmen to obtain a customized package that better for you.

Reference:

Prototype pattern

Design patterns in the test of time: Prototype

Thursday, May 22, 2014

Multiton Pattern (Registry of Singletons) in Java


Simple Note

From reference:
The multiton pattern expands on the singleton concept to manage a map of named instances as key-value pairs.
Rather than having a single instance per application (e.g. the java.lang.Runtime object in the Java programming language) the multiton pattern instead ensures a single instance per key.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/multiton

Run TestMain.java to test.

Put Vitamin into VitaminBox, there is only one VitaminBox for a kind of Vitamin.

Reference:

Multiton pattern

Wednesday, May 21, 2014

Smart Proxy Pattern in Java


Simple Note

From reference:
A smart proxy interposes additional actions when an object is accessed. Typical uses include:
Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer),
Loading a persistent object into memory when it's first referenced,
Checking that the real object is locked before it is accessed to ensure that no other object can change it.

Smart References: providing a sophisticated access to certain objects such as tracking the number of references to an object and denying access if a certain number is reached, as well as loading an object from database into memory on demand.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/smartproxy

Run TestMain.java to test.

OperatorProxy will limit the operation performed by RealOperator, at most 3 operation at a time.

Reference:

Proxy Design Pattern

Proxy Pattern

Protection Proxy Pattern in Java


Simple Note

(From Reference)
Protective Proxy – The protective proxy acts as an authorisation layer to verify if the actual user has access to appropriate content. An example can be thought about the proxy server which provides restrictive internet access in office. Only the websites and contents which are valid will be allowed and the remaining ones will be blocked.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/protectionproxy

Run TestMain.java to test.

ProxyMouseController will check role first then control mouse via RealMouseController

Reference:

Gang of Four – Proxy Design Pattern

Tuesday, May 20, 2014

Remote Proxy Pattern in Java


Simple Note

(From Reference)
Remote Proxy – A remote proxy can be thought about the stub in the RPC call. The remote proxy provides a local representation of the object which is present in the different address location. Another example can be providing interface for remote resources such as web service or REST resources.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/remoteproxy

Run TestMain.java to test.

Access Google Geo Services via GeoServiceProxy

The sample is based on Java Practice: java.net practice, Use Google Geocode Web Service

Reference:

Gang of Four – Proxy Design Pattern

Saturday, May 17, 2014

Virtual Proxy Pattern in Java


Simple Note

(From SO)
A Virtual Proxy creates expensive objects on demand

(From Wiki)
Lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/proxy/virtualproxy

Run TestMain.java to test.

ProxyFactorial will create and cache the Factorial object on demand.

Reference:

Proxy pattern

Lazy initialization

Great answer at SO

Factorial

Friday, May 16, 2014

Decorator Pattern in Java


Simple Note

(From wiki):
The decorator pattern (also known as Wrapper, an alternative naming shared with the Adapter pattern) is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/decorator

Run TestMain.java to test.

OldSiren().alarm() will only output a message in console, BeepDecorator can wrap OldSiren to add a beep.

Reference:

Decorator pattern

Grate answer at stackoverflow

Thursday, May 15, 2014

Builder Pattern in Java


Simple Note

(From wiki):
the intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern. The telescoping constructor anti-pattern occurs when the increase of object constructor parameter combination leads to an exponential list of constructors. Instead of using numerous constructors, the builder pattern uses another object, a builder, that receives each initialization parameter step by step and then returns the resulting constructed object at once.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/builder

Run TestMain.java to test.

Add base rice and lots of ingredients one by one to DonburiBuilder then build Donburi.

Reference:

Builder pattern

Grate answer at stackoverflow

Donburi

Factory Method Pattern in Java


Simple Note

(From wiki):
The essence of this pattern is to "Define an interface for creating an object, but let the classes that implement the interface decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/factory/factorymethod

Run TestMain.java to test.

abstract class Audience has a method enjoy, will get a Player to play something then enjoy.
the abstract method getPlayer can be overridden by subclass to provide different Player as needed.

Reference:

Factory method pattern (wiki)

Wednesday, May 14, 2014

Abstract Factory Pattern in Java


Simple Note

(From wiki):
The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.
(From OODesign)
Offers the interface for creating a family of related object, without explicitly specifying their classes.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/factory/abstractfactory

Run TestMain.java to test.

A FoodStore  that sells Bread from BreadFactory in odd weeks and sells PASTA from PastaFactory in even weeks.

In my opinion, Abstract Factory Pattern is most likely 'Chained Simple Factory Pattern'.

Reference:

Abstract factory pattern

Abstract Factory

Simple Factory Pattern in Java


Simple Note

Simple Factory Pattern:
A method that can return different hardcoded subtypes.

Program

https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/JAVA/DesignPattern/src/factory/simplefactory

BreadFactory that produce WonderfulBread at 3rd day of a week and produce CommonBread in other days

Can rely on the abstract class "Bread" in program, do not need to know whether it is a WonderfulBread or CommonBread

Reference:

Factory (object-oriented programming)

Simple Factory vs. Factory Method vs. Abstract Factory