工厂方法枚举

 1 package com.example.demo;
 2 
 3 public enum Factory {
 4     CIRCLE(new Circle(),"CIRCLE"),
 5     RECTANGLE(new Rectangle(),"RECTANGLE"),
 6     SQUARE(new Square(),"SQUARE");
 7 
 8     // 成员变量
 9     private Shape shape;
10     private String name;
11 
12 
13 
14     // 普通方法
15     public static Shape getShape(String name) {
16         for (Factory c : Factory.values()) {
17             if (c.name == name) {
18                 return c.shape;
19             }
20         }
21         return null;
22     }
23     // 构造方法
24     private Factory(Shape shape, String name) {
25         this.shape = shape;
26         this.name = name;
27     }
28 
29 
30 }
31 
32 class   FactoryPatternDemo{
33     public static void main(String[] args) {
34         Factory.getShape("CIRCLE").draw();
35         Factory.getShape("RECTANGLE").draw();
36         Factory.getShape("SQUARE").draw();
37     }
38 }

Inside Circle::draw() method.
Inside Rectangle::draw() method.
Inside Square::draw() method.

上一篇:Springboot项目打包启动后报错org.springframework.beans.factory.UnsatisfiedDependencyException


下一篇:Caused by:com.rabbitmq.client.ShutdownSignalException: connection error;(reply-code=530, reply-text=