// patterns/abstractfactory/GameEnvironment.java// (c)2017 MindView LLC: see Copyright.txt// We make no guarantees that this code is fit for any purpose.// Visit http://OnJava8.com for more book information.// An example of the Abstract Factory pattern// {java patterns.abstractfactory.GameEnvironment}package patterns.abstractfactory;import java.util.function.*;interface Obstacle {void action();}interface Player {void interactWith(Obstacle o);}class Kitty implements Player {@Overridepublic void interactWith(Obstacle ob) {System.out.print("Kitty has encountered a ");ob.action();}}class KungFuGuy implements Player {@Overridepublic void interactWith(Obstacle ob) {System.out.print("KungFuGuy now battles a ");ob.action();}}class Puzzle implements Obstacle {@Overridepublic void action() {System.out.println("Puzzle");}}class NastyWeapon implements Obstacle {@Overridepublic void action() {System.out.println("NastyWeapon");}}// The Abstract Factory:class GameElementFactory {Supplier<Player> player;Supplier<Obstacle> obstacle;}// Concrete factories:class KittiesAndPuzzlesextends GameElementFactory {KittiesAndPuzzles() {player = Kitty::new;obstacle = Puzzle::new;}}class KillAndDismemberextends GameElementFactory {KillAndDismember() {player = KungFuGuy::new;obstacle = NastyWeapon::new;}}public class GameEnvironment {private Player p;private Obstacle ob;publicGameEnvironment(GameElementFactory factory) {p = factory.player.get();ob = factory.obstacle.get();}public void play() {p.interactWith(ob);}public static void main(String[] args) {GameElementFactorykp = new KittiesAndPuzzles(),kd = new KillAndDismember();GameEnvironmentg1 = new GameEnvironment(kp),g2 = new GameEnvironment(kd);g1.play();g2.play();}}/* Output:Kitty has encountered a PuzzleKungFuGuy now battles a NastyWeapon*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。