|
Hello World Design Patterns
quick jump:
Creational |
Factory Method |
Abstract Factory |
Builder |
Prototype |
Singleton |
Structural |
Adapter |
Bridge |
Composite |
Decorator |
Façade |
Flyweight |
Decorator |
Behavioral |
Chain of Responsibility |
Command |
Interpreter |
Iterator |
Mediator |
Memento |
Observer |
State |
Strategy |
Template Method |
Visitor |
Model-View-Controller (MVC) |
Publish/Subscribe (pub/sub) |
Registry |
EJB Patterns |
Data Access Object (DAO)

"Hello World" is ...
A "hello world" program can be a useful sanity test to make sure that a language's compiler, development environment, and run-time environment are correctly installed. Configuring a complete programming toolchain from scratch to the point where even trivial programs can be compiled and run can involve substantial amounts of work. For this reason, a simple program is used first when testing a new tool chain.
The example program from that book prints "hello, world" (without capital letters or exclamation mark),
and was inherited from a 1974 Bell Laboratories internal memorandum by Brian Kernighan,
Programming in C: A Tutorial, which contains the first known version:
...
Code = Documentation
bad — comment inflation:
boolean flag = false; // whether has been done
good — explicit variable names:
boolean hasDone = false;
Self-documenting / self-describing code ...
http://en.wikipedia.org/wiki/Self-documenting
1 Computer Languages
1.1 C
main() {
printf("Hello world!\n");
}
1.2 BASIC
1 print "Hello world!" + CHR(13)
2 end
1.3 HP48 RPL
"Hello"
" "
"world!"
+
+
1.5 php
<?= 'Hello' . ' ' . 'world!' ?>
1.5 J2SE
package com.one0.j2se;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
} // main
} // HelloWorld
1.6 java.applet.Applet
package com.one0.applet;
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 100, 75);
} // paint
} // HelloWorld
1.7 javax.servlet.http.HttpServlet
package com.one0.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends javax.servlet.HttpServlet {
private PrintWriter out;
public doPost(HttpServletRequest req, HttpServletResponse res) {
doGet(req, res);
} // doPost
public doGet(HttpServletRequest req, HttpServletResponse res) {
res.setContentType("text/plain");
out = res.getWriter();
out.println("Hello world!");
out.flush();
} // doGet
} // HelloWorld
1.8 JSP
<%= "Hello world!" %>
<% response.flushBuffer() %>
1.9 javax.microedition.midlet.MIDlet
package com.one0.j2me;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class HelloWorld extends MIDlet implements CommandListener {
private Command exitCommand;
private TextBox tbox;
public HelloWorld() {
exitCommand = new Command("Exit", Command.EXIT, 1);
tbox = new TextBox("Hello world MIDlet", "Hello world!", 25, 0);
tbox.addCommand(exitCommand);
tbox.setCommandListener(this);
} // HelloWorld
protected void startApp() {
Display.getDisplay(this).setCurrent(tbox);
} // startApp
protected void pauseApp() {
// nothing
} // pauseApp
protected void destroyApp(boolean bool) {
// nothing
} // destroyApp
public void commandAction(Command cmd, Displayable disp) {
if (cmd == exitCommand) {
destroyApp(false);
notifyDestroyed();
} // if
} // commandAction
public static void main(String[] args) {
System.out.println("Hello world!");
} // main
} // HelloWorld
1.10 javax.swing.*
package com.one0.swing;
import javax.swing.*;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
JFrame frame = new JFrame("Hello world!");
final JLabel label = new JLabel("Hello world!");
frame.getContentPane().add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
// javax.swing.JOptionPane.showMessageDialog(null, "Hello world!");
} // main
} // HelloWorld
2 Java
2.1 java.lang.Object
java.lang.Object
2.2 access modifiers vs. visibility
access modifiers:
- public
- protected
- default
- private
class vs. method vs. variable
visibility vs. scope = lifetime
2.3 Initialization Order
- static initializer
- super.constructor
- constructor
- class variables
- instance variables
- local variables
- dangling references: NullPointerException
2.4 Instance vs. Class Variables
Class Variables
2.5 Inheritance vs. Interfaces
inheritance:
class A extends B
related:
- abstract: A class is abstract if the class or one of its methods is declared to be abstract.
It cannot be instantiated but has to be subclassed.
- final: A final class cannot be subclassed.
interface:
class B implements IB
Class B has to implement all of IB's methods or has to be declared abstract.
2.6 Inheritance vs. Associations
2.7 Multiple Inheritance
not:
class A extends B, C, D
but:
class A implements IB, IC, ID
2.8 Cloneable
Tagging interface:
java.lang.Cloneable
2.9 Serializable
Tagging interface:
java.io.Serializable
2.10 Misc
J2SE 1.4.2 API doc |
J2EE 1.4 API doc |
Android API doc
3 Creational Patterns
3.1 Factory Method
Synonyms:
Factory Method = Factory
3.1.1 The Factory
package com.one0.FactoryMethod;
public class HelloWorldFactory { // the factory
public Speaker getSpeaker("") { // the factory method
return getSpeaker("");
} // getSpeaker
public Speaker getSpeaker(String lang) { // another factory method
if (null == lang)
lang = "";
lang = lang.toLowerCase();
// dispatching creation
if (lang.equals("en"))
return new enSpeaker();
else if (lang.equals("es"))
return new esSpeaker();
else if (lang.equals("zh"))
return new zhSpeaker();
} else {
return new enSpeaker(); // default
} // else
} // getSpeaker
} // HelloWorldFactory
3.1.2 The Product Interface / Template
package com.one0.FactoryMethod;
public abstract class Speaker { // the interface (abstract template) definition
public sayHello() {
// nothing
} // sayHello
}
3.1.3 The Products
3.1.3.1 Product 1
package com.one0.FactoryMethod;
public class enSpeaker extends Speaker {
public sayHello() {
System.out.println("Hello world!");
} // sayHello
} // enSpeaker
3.1.3.2 Product 2
package com.one0.FactoryMethod;
public class esSpeaker extends Speaker {
public sayHello() {
System.out.println("iHola al mundo!");
} // sayHello
} // esSpeaker
3.1.3.3 Product 3
package com.one0.FactoryMethod;
public class zhSpeaker extends Speaker {
public sayHello() {
System.out.println("Ni hao shì jiè!");
} // sayHello
} // zhSpeaker
3.1.4 Test Driver
package com.one0.FactoryMethod;
public class Test {
public static void main(String[] args) {
HelloWorldFactory factory = new HelloWorldFactory();
Speaker sp = factory.getSpeaker(); // factory can determine what to return
sp.sayHello(); // no downcast required
} // main
} // Test
alternatively: Hello interface rather than inheriting from Hello parent class.
3.2 Abstract Factory
Synonyms:
Abstract Factory = Abstract Factory Method
- dimension 1 ("maker"): language: English, Spanish, Chinese
- dimension 2 ("family"): time: morning, noon, evening
3.2.1 The New Product Family
package com.one0.AbstractFactory;
public abstract class LangMaker { // dimension 1: language
public abstract Speaker forMorning(); // dimension 2: time
public abstract Speaker forNoon();
public abstract Speaker forEvening();
} // Maker
3.2.2 Product Makers
3.2.2.1 Product Maker A
package com.one0.AbstractFactory;
public class enMaker extends LangMaker { // dimension 1: sort of a meta factory for English speakers
public Speaker forMorning() { // dimension 2: time
return new GenericSpeaker("Good morning world!"); // product A/1
// alternatively:
// dedicated class EnMorningSpeaker extends Speaker
} // forMorning
public Speaker forNoon() {
return new GenericSpeaker("Good day world!"); // product A/2
// forNoon
public Speaker forEvening() {
return new GenericSpeaker("Good evening world!"); // product A/3
} // forEvening
} // enMaker
3.2.2.2 Product Maker B
package com.one0.AbstractFactory;
public class esMaker extends LangMaker { // // dimension 1: sort of a meta factory for Spanish speakers
public Speaker forMorning() { // dimension 2: time
return new GenericSpeaker("iBuenos dias al mundo!"); // product B/1
} // forMorning
public Speaker forNoon() {
return new GenericSpeaker("iBuenas tardes al mundo!"); // product B/2
// forNoon
public Speaker forEvening() {
return new GenericSpeaker("iBuenas noches al mundo!"); // product B/3
} // forEvening
} // esMaker
3.2.2.3 Product Maker C
package com.one0.AbstractFactory;
public class zhMaker extends LangMaker { // dimension 1: sort of a meta factory for Chinese Speakers
public Speaker forMorning() { // dimension 2: time
return new GenericSpeaker("Ni zao shì jiè!"); // product C/1
} // forMorning
public Speaker forNoon() {
return new GenericSpeaker("Ni hao shì jiè!"); // product C/2
// forNoon
public Speaker forEvening() {
return new GenericSpeaker("Wan an shì jiè!"); // product C/3
} // forEvening
} // zhMaker
3.2.3 The Abstract Factory
package com.one0.AbstractFactory;
public class HelloWorldFactory { // the (abstract) factory -- not itself declared abstract
public final static int MORNING = 0;
public final static int NOON = 1;
public final static int EVENING = 2;
private int time;
private Maker mk; // dimension 2: time
private Speaker sp; // dimension 1: for the specific language (at the given time)
public void setTime(int time) {
this.time = time;
} // setTime
public Speaker getSpeaker("") { // the factory method
return getSpeaker("");
} // getSpeaker
public Speaker getSpeaker(String lang) { // another factory method
if (null == lang)
lang = "";
lang = lang.toLowerCase();
// dimension 1: dispatching language
if (lang.equals("en"))
mk = new enMaker();
else if (lang.equals("es"))
mk = new esMaker();
else if (lang.equals("zh"))
mk = new zhMaker();
} else {
mk = new enMaker(); // default
} // else
// dimension 2: dispatching time
if (NOON == time) {
return mk.forNoon();
} else if (EVENING == time) {
return mk.forEvening();
} else {
return mk.forMorning(); // default
} // else
/*
specifically:
- tries to avoid n x m number of classes ("class explosion") by parameterizing behavior
- reduces number of classes to n + m = number of language makers + number of times
generally:
- reduces 2-dimensional dispatching to a centralized, sequential dispatching sequence
- could even be more than those 2 dimensions
*/
} // getSpeaker
} // HelloWorldFactory
3.2.4 Product Interface / Template
package com.one0.AbstractFactory;
public abstract Speaker { // the interface (abstract template) definition
public sayHello() {
// nothing
} // sayHello
}
3.2.5 Generic (Parameterized) Product
package com.one0.AbstractFactory;
public GenericSpeaker extends Speaker {
private msg = "";
public Speaker(msg) { // parameterized here to avoid class explosion
this.msg = msg;
} // Speaker
public sayHello() {
System.out.println(msg);
} // sayHello
} // GenericSpeaker
3.2.6 Test Driver
package com.one0.AbstractFactory;
public class Test {
public static void main(String[] args) {
HelloWorldFactory factory = new HelloWorldFactory();
factory.setTime(HelloWorldFactory.MORNING); // set the time context once (dimension 2)
Speaker sp = factory.getSpeaker(); // factory decides about language context (dimension 1)
sp.sayHello();
} // main
} // Test
Grouping / dimensions could also be the other way round —
e. g. Maker producing Speakers by time:
package com.one0.AbstractFactory;
public abstract class TimeMaker { // dimension 1: time
public abstract Speaker forEn(); // dimension 2: language
public abstract Speaker forEs();
public abstract Speaker forZh();
} // TimeMaker
This then results in respective concrete Makers, e. g.:
package com.one0.AbstractFactory;
public class MorningMaker extends TimeMaker { // dimension 2: sort of a meta factory for Morning greetings
public Speaker forEn() { // dimension 1: language
return new GenericSpeaker("Good morning world!"); // product A/1
// alternatively:
// dedicated class EnMorningSpeaker extends Speaker
} // forEn
public Speaker forEs() {
return new GenericSpeaker("iBuenos dias al mundo!"); // product B/1
// forEs
public Speaker forZh() {
return new GenericSpeaker("Ni zhao!"); // product C/1
} // forZh
} // MorningMaker
3.3 Builder
3.4 Prototype
3.4.1 The Cloneable Template
package com.one0.Prototype;
public class Prototype implements Cloneable {
// http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#clone()
private String msg = "Hello world!";
public Prototype(String msg) {
this.msg = msg;
} // msg
public void setMsg(String msg) {
this.msg = msg;
} // setMsg
public void sayHello() {
System.out.println(msg);
} // sayHello
protected Object clone() {
Object o = null;
try {
o = super.clone();
} // try
catch (Exception e) {
System.out.println("Error during cloning");
} // catch
return o;
} // clone
public Prototype pubClone() {
return (Prototype)clone();
} // pubClone
} // Prototype
3.4.2 The Client
package com.one0.Prototype;
public class Test {
public static void main(String[] args) {
Prototype myP = new Prototype("hello world!");
myP.sayHello();
Prototype myP2 = myP.pubClone();
myP.sayHello();
myP.setMsg("iHola al mundo!");
myP.sayHello();
System.out.println(myP + " vs. " + myP2);
} // main
} // Test
3.5 Singleton
3.5.1 Singleton Type 1
private constructor and static method(s),
i. e. the java.lang.Math approach:
package com.one0.singleton.type1;
public final class HelloWorld {
static boolean isCreated = false;
private HelloWorld { // private - cannot construct from outside
// nothing
} // HelloWorld
public static void sayHello() {
System.out.println("Hello world!");
} // sayHello
} // HelloWorld
3.5.2 Singleton Type 2
private state variable and check in the public constructor:
package com.one0.singleton.type2;
public final class HelloWorld {
static private boolean isCreated = false;
public HelloWorld throws Exception {
if (isCreated) {
throw new Exception("Only one instance allowed!");
} // if
else {
isCreated = true;
System.out.println("Hello world!");
} // HelloWorld
public static void sayHello() {
System.out.println("Hello world!");
} // sayHello
} // HelloWorld
3.5.3 Singleton Type 3
private self reference, private constructor, getInstance() method similar to Factory Method,
and returning same reference upon repeated requests:
package com.one0.singleton.type3;
public final class HelloWorld {
static private HelloWorld hw = null;
private HelloWorld { // private constructor can only be referred from this object
System.out.println("Hello world!");
} // HelloWorld
static public HelloWorld getInstance() { // lazy initialisation
if (null == hw) {
hw = new HelloWorld();
} // if
return (hw);
} // HelloWorld
public static void sayHello() {
System.out.println("Hello world!");
} // sayHello
public void finalize() {
hw = null;
} // finalize
} // HelloWorld
3.5.4 n instances
n instances are managed by a Pool Manager which itself is a Singleton.
4 Structural Patterns
4.1 Adapter
4.2 Bridge
4.3 Composite
4.4 Decorator
4.5 Façade
4.6 Flyweight
4.7 Decorator
5 Behavioral Patterns
5.1 Chain of Responsibility
5.2 Command
5.3 Interpreter
5.4 Iterator
5.5 Mediator
5.6 Memento
5.7 Observer
5.8 State
5.9 Strategy
5.10 Template Method
5.11 Visitor
6 Misc.
6.1 Model-View-Controller
6.1.1 Model
package com.one0.MVC;
public class Model { // the "data"
private String text; // the data model
private View[] v;
public attach(View v) {
this.v[v.length++] = v; // rewrite to use collection / iterator
} // attach
public String getData() {
return (text);
} // getText
public String addData(String text) {
this.text = text;
} // addText
private notify() {
for(int i = 0, i < v.length[]; i++)
v[i].update();
} // notify
} // Model
6.1.2 View
package com.one0.MVC;
public interface View {
public Controller initialize(Model m);
public void display();
} // View
package com.one0.MVC;
public class TextView implements View {
private Model;
public Controller initialize(Model m) {
this.m = m;
Controller c = null;
if (true)
c = new TextController();
return (c);
} // initialize
public void display() {
System.out.println(m.getData());
} // display
} // TextView
package com.one0.MVC;
public class GUIView implements View {
private Model;
private ...JFrame jf...
public Controller initialize(Model m) {
this.m = m;
Controller c = null;
if (true)
c = new GUIController();
return (c);
} // initialize
public void display() {
jf ... m.getData());
} // display
} // GUIView
6.1.3 Controller
package com.one0.MVC;
public abstract class Controller {
private Model m = null;
public Controller(Model m) {
this.m = m;
} // Controller
public void handleEvent(Object o);
} // Controller
package com.one0.MVC;
public class TextController extends Controller {
public TextController(Model m) {
super(m);
} // GUIController
public void handleEvent(Object o) {
m.addData(o.toString());
} // handleEvent
} // TextController
package com.one0.MVC;
public class GUIController extends Controller {
public GUI(Model m) {
super(m);
...set up GUI...
} // GUIController
public void handleEvent(Object o) {
m.addData(o.toString());
} // handleEvent
} // GUIController
6.1.4 MVC Application
package com.one0.MVC;
public class MVCApplication {
public static void main(String[] args) {
Model m = new Model("Hello world!");
View vText = new TextView();
Controller cText = vText.initialize(m);
cText.handleEvent(args[0]);
View vGUI = new GUIView();
Controller cGUI = vText.initialize(m);
cText.handleEvent(args[0]);
6.1.5 Interaction Diagram
--update-->
Controller(s) --> Model View(s)
^ <--getData-- !
!-------------------handleEvent--
6.2 Publish/Subscribe
6.3 Registry
6.4 EJB Patterns
6.4.1 Data Access Object
7 References
|