设计模式(二)-----工厂模式
工厂模式(Factory Pattern)属于创建型模式的一种,简单的说就是通过输入参数调用工厂类创建产品的方法创建出相应的产品。

代码如下:
1、Ball
/** * Created with IntelliJ IDEA. * Description: 产品-球 * User: guaniu * Date: 2020.11.27 15:08 */ public interface Ball { void playBall(); }
2、BlackBall
/** * Created with IntelliJ IDEA. * Description: 产品-黑球 * User: guaniu * Date: 2020.11.27 15:13 */ public class BlackBall implements Ball{ @Override public void playBall() { System.out.println("Playing BlackBall!"); } }
3、GreenBall
/** * Created with IntelliJ IDEA. * Description: 产品-绿球 * User: guaniu * Date: 2020.11.27 15:11 */ public class GreenBall implements Ball{ @Override public void playBall() { System.out.println("Playing GreenBall!"); } }
4、RedBall
/** * Created with IntelliJ IDEA. * Description: 产品-红球 * User: guaniu * Date: 2020.11.27 15:12 */ public class RedBall implements Ball{ @Override public void playBall() { System.out.println("Playing RedBall!"); } }
5、BallFactory
/** * Created with IntelliJ IDEA. * Description: 工厂-球 * User: guaniu * Date: 2020.11.27 15:09 */ public class BallFactory { Ball getBall(String color){ if ("red".equalsIgnoreCase(color)){ return new RedBall(); }else if ("green".equalsIgnoreCase(color)){ return new GreenBall(); }else if ("black".equalsIgnoreCase(color)){ return new BlackBall(); }else { try { throw new Exception("No Such Type of Ball!"); } catch (Exception e) { e.printStackTrace(); } } return null; } }
6、测试
/** * Created with IntelliJ IDEA. * Description: * User: guaniu * Date: 2020.11.27 15:26 */ public class Test { public static void main(String[] args){ String[] colors = {"red", "black", "green"}; Random random = new Random(); BallFactory ballFactory = new BallFactory(); for (int i = 0; i < 10; i++){ String color = colors[random.nextInt(3)]; Ball ball = ballFactory.getBall(color); if (ball != null){ ball.playBall(); } } } }
结果:

项目中的应用场景:
JUC 中的ThreadFactory线程工厂;

浙公网安备 33010602011771号