例一:
interfaceService
{
void method1();
void method2();
}
interfaceServiceFactory
{
Service getService();
}
classImplementation1 implements Service
{
private Implementation1(){}
public voidmethod1(){System.out.println("Implementation1 method1");}
public voidmethod2(){System.out.println("Implementation1 method2");}
public static ServiceFactory factory =
new ServiceFactory(){
public Service getService(){
return new Implementation1();
}
};
}
classImplementation2 implements Service
{
private Implementation2(){}
public voidmethod1(){System.out.println("Implementation2 method1");}
public voidmethod2(){System.out.println("Implementation2 method2");}
public static ServiceFactory factory =
new ServiceFactory(){
public Service getService(){
return new Implementation2();
}
};
}
publicclass Factories
{
public static voidserviceConsumer(ServiceFactory fact)
{
Service s = fact.getService();
s.method1();
s.method2();
}
public static void main(String[] args)
{
serviceConsumer(Implementation1.factory);
serviceConsumer(Implementation2.factory);
}
}
例二:
interfaceGame
{
boolean move();
}
interfaceGameFactory
{
Game getGame();
}
classCheckers implements Game
{
private Checkers(){}
private int moves = 0;
private static final int MOVES = 3;
public boolean move()
{
System.out.println("Checkers move" + moves);
return ++moves != MOVES;
}
public static GameFactory factory = new GameFactory()
{
public Game getGame(){return newCheckers();}
};
}
classChess implements Game
{
private Chess(){}
private int moves = 0;
private static final int MOVES = 4;
public boolean move()
{
System.out.println("Chess move "+ moves);
return ++moves != MOVES;
}
public static GameFactory factory = newGameFactory(){
public Game getGame(){return new Chess();}
};
}
publicclass Games
{
public static void playGame(GameFactoryfactory){
Game s = factory.getGame();
while(s.move())
;
}
public static void main(String[] arg)
{
playGame(Checkers.factory);
playGame(Chess.factory);
}
}