手写工厂模式
public class FactoryMethod {
public interface Shape {
void draw();
}
public interface Factory {
Shape getShape();
}
public static class Circle implements Shape {
public Circle() {
System.out.println("Circle");
}
@Override
public void draw() {
System.out.println("Draw Circle");
}
}
public static class Rectangle implements Shape {
public Rectangle() {
System.out.println("Rectangle");
}
@Override
public void draw() {
System.out.println("Draw Rectangle");
}
}
public static class Square implements Shape {
public Square() {
System.out.println("Square");
}
@Override
public void draw() {
System.out.println("Draw Square");
}
}
public static class CircleFactory implements Factory {
@Override
public Shape getShape() {
return new Circle();
}
}
public class RectangleFactory implements Factory {
@Override
public Shape getShape() {
return new Rectangle();
}
}
public class SquareFactory implements Factory {
@Override
public Shape getShape() {
return new Square();
}
}
public static void main(String[] args) {
FactoryMethod.Factory circlefactory = new FactoryMethod.CircleFactory();
FactoryMethod.Shape circle = circlefactory.getShape();
circle.draw();
}
}