Home » design pattern
Category Archives: design pattern
Using interfaces for writing DAO classes
What is dependency injection?
public SomeClass() {
myObject = Factory.getObject();
}
public SomeClass (MyClass myObject) {
this.myObject = myObject;
}
Where exactly the Singleton Pattern is used in real application?
LogManager
– there’s a static LogManager.getLogManager()
method, and a single global instance is used.In fact this isn’t a “true” singleton as you can derive your own class from
LogManager
and create extra instances that way – but it’s typically used as a singleton.Another example would be
java.lang.Runtime
– from the docs:
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.
That’s pretty much the definition of a singleton 🙂
Now the singleton pattern is mostly frowned upon these days – it introduces tight coupling, and makes things which use the singleton harder to test, as you can’t easily mock out that component. If you can get away without it, so much the better. Inject your dependencies where possible instead.
Using Command Design pattern
public interface Command {
public void execute();
}
public final class StopServerCommand implements Command {
private final Server server;
public StopServerCommand(Server server) { this.server = server; }
public void execute() {
if(server.isRunning()) server.stop();
}
}
public class Application {
//...
public void someMethod() {
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(Event e) {
stopCommand.execute();
}
});
}
}
http://stackoverflow.com/questions/2015549/using-command-design-pattern
Factory Pattern. When to use factory methods?
public interface IThingFactory
{
Thing GetThing(string theString);
}
public class ThingFactory : IThingFactory
{
public Thing GetThing(string theString)
{
return new Thing(theString, firstDependency, secondDependency);
}
}
http://stackoverflow.com/questions/69849/factory-pattern-when-to-use-factory-methods
Strategy Pattern
In computer programming, the strategy pattern (also known as the policy pattern) is a particular software design pattern, whereby algorithms can be selected at runtime. Formally speaking, the 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. package org.wikipedia.strategy; // The classes that implement a concrete strategy should implement this // The context class uses this to call the concrete strategy interface Strategy { int execute(int a, int b); } // Implements the algorithm using the strategy interface class ConcreteStrategyAdd implements Strategy { public int execute(int a, int b) { System.out.println(“Called ConcreteStrategyAdd’s execute()”); return a + b; // Do an addition with a and b } } class ConcreteStrategySubtract implements Strategy { public int execute(int a, int b) { System.out.println(“Called ConcreteStrategySubtract’s execute()”); return a – b; // Do a subtraction with a and b } } class ConcreteStrategyMultiply implements Strategy { public int execute(int a, int b) { System.out.println(“Called ConcreteStrategyMultiply’s execute()”); return a * b; // Do a multiplication with a and b } } // Configured with a ConcreteStrategy object and maintains a reference to a // Strategy object class Context { private Strategy strategy; // Constructor public Context(Strategy strategy) { this.strategy = strategy; } public int executeStrategy(int a, int b) { return strategy.execute(a, b); } } // StrategyExample test application class StrategyExample { public static void main(String[] args) { Context context; // Three contexts following different strategies context = new Context(new ConcreteStrategyAdd()); int resultA = context.executeStrategy(3, 4); context = new Context(new ConcreteStrategySubtract()); int resultB = context.executeStrategy(3, 4); context = new Context(new ConcreteStrategyMultiply()); int resultC = context.executeStrategy(3, 4); } }
Called ConcreteStrategyAdd's execute()
Called ConcreteStrategySubtract's execute()
Called ConcreteStrategyMultiply's execute()
Template Design Pattern
You have a base class with a template method that lists actions you want to execute. Inheriting class is what actually implements methods customizing them as appropriate for the type of robot that you are creating. package template; public abstract class RobotTemplate { public final void go() { start(); getParts(); assemble(); test(); stop(); } public void start() { System.out.println(“Starting….”); } public void getParts() { System.out.println(“Getting parts….”); } public void assemble() { System.out.println(“Assembling….”); } public void test() { System.out.println(“Testing….”); } public void stop() { System.out.println(“Stopping….”); } } package template; public class CookieRobot extends RobotTemplate { private String name; public CookieRobot(String n) { name = n; } public void getParts() { System.out.println(“Getting a flour and sugar….”); } public void assemble() { System.out.println(“Baking a cookie….”); } public void test() { System.out.println(“Crunching a cookie….”); } public String getName() { return name; } } package template; public class AutomotiveRobot extends RobotTemplate { private String name; public AutomotiveRobot(String n) { name = n; } public void getParts() { System.out.println(“Getting a carburetor….”); } public void assemble() { System.out.println(“Installing the carburetor….”); } public void test() { System.out.println(“Revving the engine….”); } public String getName() { return name; } } package template; public class TestTemplate { public static void main(String args[]) { AutomotiveRobot automotiveRobot = new AutomotiveRobot(“Automotive Robot”); CookieRobot cookieRobot = new CookieRobot(“Cookie Robot”); System.out.println(automotiveRobot.getName() + “:”); automotiveRobot.go(); System.out.println(); System.out.println(cookieRobot.getName() + “:”); cookieRobot.go(); } }
Automotive Robot:
Starting....
Getting a carburetor....
Installing the carburetor....
Revving the engine....
Stopping....
Cookie Robot:
Starting....
Getting a flour and sugar....
Baking a cookie....
Crunching a cookie....
Stopping....
package template_hook; // a template with a hook public abstract class RobotHookTemplate { public final void go() { start(); getParts(); assemble(); if (testOK()){ test(); } stop(); } public void start() { System.out.println(“Starting….”); } public void getParts() { System.out.println(“Getting parts….”); } public void assemble() { System.out.println(“Assembling….”); } public void test() { System.out.println(“Testing….”); } public void stop() { System.out.println(“Stopping….”); } public boolean testOK() { return true; } } package template_hook; public class CookieHookRobot extends RobotHookTemplate { private String name; public CookieHookRobot(String n) { name = n; } public void getParts() { System.out.println(“Getting a flour and sugar….”); } public void assemble() { System.out.println(“Baking a cookie….”); } public String getName() { return name; } public boolean testOK() { return false; } } package template_hook; public class TestHookTemplate { public static void main(String args[]) { CookieHookRobot cookieHookRobot = new CookieHookRobot(“Cookie Robot”); System.out.println(cookieHookRobot.getName() + “:”); cookieHookRobot.go(); } }
Cookie Robot:
Starting....
Getting a flour and sugar....
Baking a cookie....
Stopping....
Java Design Pattern – Business Delegate
- business delegate that is the object used by clients to request for services;
- lookup service is a bridge used by business delegate to search for services, it encapsulates the search algorithm according to the request made by the delegate;
- business service is the actual service that is offered to clients, usually an EJB or similar J2EE concepts.
By the way this page explains everything quite clearly..
http://stackoverflow.com/questions/2502772/java-design-pattern-business-delegate
Factory Design Pattern
Idea is you extract the volatile core code and put it into external factory object. package factory; public abstract class Connection { public Connection() { } public String description() { return “Generic”; } } package factory; public class FirstFactory { String type; public FirstFactory(String t) { type = t; } // handle volatile code public Connection createConnection() { if (type.equals(“Oracle”)) { return new OracleConnection(); } else if (type.equals(“SQL Server”)) { return new SqlServerConnection(); } else { return new MySqlConnection(); } } } package factory; public class MySqlConnection extends Connection { public MySqlConnection() { } public String description() { return “MySQL”; } } package factory; public class OracleConnection extends Connection { public OracleConnection() { } public String description() { return “Oracle”; } } package factory; public class SqlServerConnection extends Connection { public SqlServerConnection() { } public String description() { return “SQL Server”; } } package factory; public class TestConnection { public static void main(String args[]) { FirstFactory factory; factory = new FirstFactory(“Oracle”); Connection connection = factory.createConnection(); System.out.println(“You’re connecting with ” + connection.description()); factory = new FirstFactory(“SQL Server”); connection = factory.createConnection(); System.out.println(“You’re connecting with ” + connection.description()); factory = new FirstFactory(“MySQL”); connection = factory.createConnection(); System.out.println(“You’re connecting with ” + connection.description()); } } Instead of configuring factory at the time of construction (usual in Java), GoF factory design pattern says you should be able to create a general factory and then set the type of connection at the time of connection creation. package factory.gof; public abstract class Connection { public Connection() { } public String description() { return “Generic”; } } package factory.gof; public abstract class ConnectionFactory { public ConnectionFactory() { } protected abstract Connection createConnection(String type); } package factory.gof; public class SecureFactory extends ConnectionFactory { public Connection createConnection(String type) { if (type.equals(“Oracle”)) { return new SecureOracleConnection(); } else if (type.equals(“SQL Server”)) { return new SecureSqlServerConnection(); } else { return new SecureMySqlConnection(); } } } package factory.gof; public class SecureMySqlConnection extends Connection { public SecureMySqlConnection() { } public String description() { return “MySQL secure”; } } package factory.gof; public class SecureOracleConnection extends Connection { public SecureOracleConnection() { } public String description() { return “Oracle secure”; } } package factory.gof; public class SecureSqlServerConnection extends Connection { public SecureSqlServerConnection() { } public String description() { return “SQL Server secure”; } } package factory.gof; public class TestFactory { public static void main(String args[]) { SecureFactory factory; factory = new SecureFactory(); Connection connection = factory.createConnection(“Oracle”); System.out.println(“You’re connecting with ” + connection.description()); connection = factory.createConnection(“SQL Server”); System.out.println(“You’re connecting with ” + connection.description()); connection = factory.createConnection(“MySQL”); System.out.println(“You’re connecting with ” + connection.description()); } }