Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created February 14, 2013 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/4950348 to your computer and use it in GitHub Desktop.
Save JoshCheek/4950348 to your computer and use it in GitHub Desktop.
Java Factory example
class A {
public static void main(String[] Args) {
A a = new A(new B1Factory());
System.out.println(a);
a = new A(new B2Factory());
System.out.println(a);
}
private BFactory factory;
public A(BFactory factory) { this.factory = factory; }
public String toString() {
return "<A containing the b: " + factory.b() + ">";
}
static interface BFactory {
public B b();
}
static interface B {
public String toString();
}
static class B1Factory implements BFactory {
public B b() { return new B1(); }
}
static class B1 implements B {
public String toString() { return "b1"; }
}
static class B2Factory implements BFactory {
public B b() { return new B2(); }
}
static class B2 implements B {
public String toString() { return "b2"; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment