97 lines
2.0 KiB
Java
Raw Normal View History

2017-01-08 22:55:49 -08:00
// patterns/abstractfactory/GameEnvironment.java
2020-10-07 13:35:40 -06:00
// (c)2020 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// An example of the Abstract Factory pattern
2017-01-08 22:55:49 -08:00
// {java patterns.abstractfactory.GameEnvironment}
package patterns.abstractfactory;
2015-11-03 12:00:44 -08:00
import java.util.function.*;
2015-06-15 17:47:35 -07:00
interface Obstacle {
void action();
}
interface Player {
void interactWith(Obstacle o);
}
class Kitty implements Player {
@Override
public void interactWith(Obstacle ob) {
System.out.print("Kitty has encountered a ");
ob.action();
}
}
class KungFuGuy implements Player {
@Override
public void interactWith(Obstacle ob) {
System.out.print("KungFuGuy now battles a ");
ob.action();
}
}
class Puzzle implements Obstacle {
@Override
public void action() {
System.out.println("Puzzle");
}
}
class NastyWeapon implements Obstacle {
@Override
public void action() {
System.out.println("NastyWeapon");
}
}
// The Abstract Factory:
2015-11-03 12:00:44 -08:00
class GameElementFactory {
Supplier<Player> player;
Supplier<Obstacle> obstacle;
2015-06-15 17:47:35 -07:00
}
// Concrete factories:
class KittiesAndPuzzles
2015-11-03 12:00:44 -08:00
extends GameElementFactory {
KittiesAndPuzzles() {
player = Kitty::new;
obstacle = Puzzle::new;
2015-06-15 17:47:35 -07:00
}
}
class KillAndDismember
2015-11-03 12:00:44 -08:00
extends GameElementFactory {
KillAndDismember() {
player = KungFuGuy::new;
obstacle = NastyWeapon::new;
2015-06-15 17:47:35 -07:00
}
}
public class GameEnvironment {
private Player p;
private Obstacle ob;
2015-11-03 12:00:44 -08:00
public
GameEnvironment(GameElementFactory factory) {
p = factory.player.get();
ob = factory.obstacle.get();
2015-06-15 17:47:35 -07:00
}
public void play() {
p.interactWith(ob);
}
2016-01-25 18:05:55 -08:00
public static void main(String[] args) {
2015-06-15 17:47:35 -07:00
GameElementFactory
kp = new KittiesAndPuzzles(),
kd = new KillAndDismember();
GameEnvironment
g1 = new GameEnvironment(kp),
g2 = new GameEnvironment(kd);
g1.play();
g2.play();
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Kitty has encountered a Puzzle
KungFuGuy now battles a NastyWeapon
2015-09-07 11:44:36 -06:00
*/