设计模式

1.工厂模式

public interface Shape {
   void draw();
}
public class Rectangle implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
   }
}
public class Square implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Square::draw() method.");
   }
}
public class Circle implements Shape {
   @Override
   public void draw() {
      System.out.println("Inside Circle::draw() method.");
   }
}
public class ShapeFactory {
   public static <T> T getClass(Class clazz) {
        T obj = null;
        try {
            obj = (T) clazz.getConstructor().newInstance();
        } catch (ReflectiveOperationException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
public class FactoryPatternDemo {
   public static void main(String[] args) {
      Circle circle = (Circle)shapeFactory.getClass(Circle.class);
      circle.draw();
      Rectangle rec = shapeFactory.getClass(Rectangle.class);
      rec.draw();
      Square square = shapeFactory.getClass(Square.class);
      square.draw();
   }
}

2.

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页