简介:工厂类根据传入参数,创建对应的实现类
目的:根据传入参数,提供对应的实现类
总结:工厂类根据传入参数,创建对应的实现类
主要组成: 接口, 实现类, 工厂类
接口:
GameService.java
package com.design.c.factory.simple; public interface GameService { /** * 游戏方法 */ void play(); }
实现类:
AGameServiceImpl.java
package com.design.c.factory.simple; public class AGameServiceImpl implements GameService { @Override public void play() { System.out.println("Playing AngryBird Game ... ... "); } }
BGameServiceImpl.java
package com.design.c.factory.simple; public class BGameServiceImpl implements GameService { @Override public void play() { System.out.println("Playing LOL Game ... ... "); } }
工厂类:
package com.design.c.factory.simple; /** * 简单工厂模式 * * 简介:由一个工厂对象决定创建出哪一种实例 */ public class SimpleFactory { //1-私有化构造方法 private SimpleFactory(){}; //2-根据传递给工厂类的参数,决定创建那种实例 public static GameService createGameService(String gameName){ if(gameName == null){ return null; } if("A".equals(gameName)){ return new AGameServiceImpl(); }else if("B".equals(gameName)){ return new BGameServiceImpl(); } return null; } }
Main:
package com.design.c.factory.simple; public class MainTest { public static void main(String[] args) { /** * 3-简单工厂模式 */ GameService lolGame = SimpleFactory.createGameService("A"); lolGame.play(); GameService angryBirdGame = SimpleFactory.createGameService("B"); angryBirdGame.play(); } }
Result:
Playing AngryBird Game ... ... Playing LOL Game ... ...
时间: 2024-11-05 20:42:35