What is a Domain Model

Basically, it’s the “model” of the objects required for your business purposes.
Say you were making a sales tracking website – you’d potentially have classes such as Customer, Vendor, Transaction, etc. That entire set of classes, as well as the relationships between them, would consititute yourDomain Model.

Using interfaces for writing DAO classes

NOTE THAT : You should always try to separating the Interface from the Implementation. This will give you more control to the other layers, using this DAO layer.
But, As you know an interface gives you more abstraction, and makes the code more flexible and resilient to changes, because you can use different implementations of the same interface without changing its client. Still, if you don’t think your code will change, or (specially) if you think your abstraction is good enough, you don’t necessarily have to use interfaces
In other words: interfaces are good, but before making an interface for every class think about it

What is dependency injection?

Basically, instead of having your objects creating a dependency or asking a factory object to make one for them, you pass the needed dependencies in to the constructor, and you make it somebody else’s problem (an object further up the dependency graph, or a dependency injector that builds the dependency graph). A dependency as I’m using it here is any other object the current object needs to hold a reference to.
One of the major advantages of dependency injection is that it can make testing lots easier. Suppose you have an object which in its constructor does something like:
public SomeClass() {
myObject = Factory.getObject();
}
This can be troublesome when all you want to do is run some unit tests on SomeClass, especially if myObject is something that does complex disk or network access. So now you’re looking at mocking myObject but also somehow intercepting the factory call. Hard. Instead, pass the object in as an argument to the constructor. Now you’ve moved the problem elsewhere, but testing can become lots easier. Just make a dummy myObject and pass that in. The constructor would now look a bit like:
public SomeClass (MyClass myObject) {
this.myObject = myObject;
}
Most people can probably work out the other problems that might arise when not using dependency injection while testing (like classes that do too much work in their constructors etc.) Most of this is stuff I picked up on the Google Testing Blog, to be perfectly honest…

Where exactly the Singleton Pattern is used in real application?

Typically singletons are used for global configuration. The simplest example would be 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.

http://stackoverflow.com/questions/3192095/where-exactly-the-singleton-pattern-is-used-in-real-application

Using Command Design pattern

public interface Command {
   
public void execute();
}
For the most part, commands are immutable and contain instructions that encapsulate a single action that is executed on demand. You might also have a RuntimeCommand that accepts instructions upon execution, but this delves more into the Strategy or Decorator Patterns depending on the implementations.
In my own opinion, I think it’s very important to heed the immutable context of a command otherwise the command becomes a suggestion. For instance:
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();
           
}
       
});
   
}
}
I personally don’t really like commands. In my own experience, they only work well for framework callbacks.
If it helps, think of a command in a metaphorical sense; a trained soldier is given a command by his/her commanding officer, and on demand the soldier executes this command.

http://stackoverflow.com/questions/2015549/using-command-design-pattern

Factory Pattern. When to use factory methods?

I like thinking about design pattens in terms of my classes being ‘people,’ and the patterns are the ways that the people talk to each other.
So, to me the factory pattern is like a hiring agency. You’ve got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that’s it.
So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually hire someone, you need to know a lot of stuff – benefits, eligibility verification, etc. But the person hiring doesn’t need to know any of this – the hiring agency handles all of that.
In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they’re created, or what their dependencies are – they only have to give the information they actually want.
public interface IThingFactory
{
Thing GetThing(string theString);
}

public class ThingFactory : IThingFactory
{
public Thing GetThing(string theString)
{
return new Thing(theString, firstDependency, secondDependency);
}
}
So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer.

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()

http://en.wikipedia.org/wiki/Strategy_pattern

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

The business delegate pattern tries to decouple the clients from the business services. To achieve this you need:

  • 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()); } }