Java Tutorial/Design Pattern/Abstract Factory Pattern

Материал из Java эксперт
Перейти к: навигация, поиск

An example of the Abstract Factory pattern.

   <source lang="java">

interface Ball {

 void action();

} interface Player {

 void kick(Ball o);

} class PlayerA implements Player {

 public void kick(Ball ob) {
   System.out.print("Player A");
   ob.action();
 }

} class PlayerB implements Player {

 public void kick(Ball ob) {
   System.out.print("Player B");
   ob.action();
 }

} class BasketBall implements Ball {

 public void action() {
   System.out.println("Hand pass");
 }

} class Football implements Ball {

 public void action() {
   System.out.println("Foot pass");
 }

} // The Abstract Factory: interface AbstractGameFactory {

 Player makePlayer();
 Ball makeObstacle();

} // Concrete factories: class BasketBallFactory implements AbstractGameFactory {

 public Player makePlayer() {
   return new PlayerA();
 }
 public Ball makeObstacle() {
   return new BasketBall();
 }

} class FootballFactory implements AbstractGameFactory {

 public Player makePlayer() {
   return new PlayerB();
 }
 public Ball makeObstacle() {
   return new Football();
 }

} class Match {

 private Player p;
 private Ball ob;
 public Match(AbstractGameFactory factory) {
   p = factory.makePlayer();
   ob = factory.makeObstacle();
 }
 public void play() {
   p.kick(ob);
 }

} public class Games {

 public static void main(String args[]) {
   AbstractGameFactory kp = new BasketBallFactory(), kd = new FootballFactory();
   Match g1 = new Match(kp), g2 = new Match(kd);
   g1.play();
   g2.play();
 }

}</source>