Skip to content

Instantly share code, notes, and snippets.

@tsu-nera
Created December 10, 2014 12:55
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 tsu-nera/db8a24ed41d6806f4187 to your computer and use it in GitHub Desktop.
Save tsu-nera/db8a24ed41d6806f4187 to your computer and use it in GitHub Desktop.
FactoryMethod Pattern
// http://ja.wikipedia.org/wiki/Factory_Method_%E3%83%91%E3%82%BF%E3%83%BC%E3%83%B3
public class FactoryMethodSample {
public static void main(String[] args) {
Creator creator;
Product product;
creator = new CreatorA();
product = creator.factoryMethod();
product.whoAreYou();
creator = new CreatorB();
product = creator.factoryMethod();
product.whoAreYou();
}
}
abstract class Creator {
abstract Product factoryMethod();
}
class CreatorA extends Creator {
Product factoryMethod() {
return new ProductA();
}
}
class CreatorB extends Creator {
Product factoryMethod() {
return new ProductB();
}
}
abstract class Product {
abstract void whoAreYou();
}
class ProductA extends Product {
void whoAreYou() { System.out.println("I'm A");}
}
class ProductB extends Product {
void whoAreYou() { System.out.println("I'm B");}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment