将抽象部分与它的实现部分分离,使它们都可以独立地变化。
public abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
abstract void draw();
}
public class Circle extends Shape {
public Circle(Color color) {
super(color);
}
@Override
void draw() {
System.out.println(color.getColor() + " Circle");
}
}
public class Square extends Shape {
public Square(Color color) {
super(color);
}
@Override
void draw() {
System.out.print(color.getColor() + " Square");
}
}
public interface Color {
String getColor();
}
public class Red implements Color {
@Override
public String getColor() {
return "Red";
}
}
public class Green implements Color {
@Override
public String getColor() {
return "Green";
}
}
public class Client {
public static void main(String[] args) {
Shape redCircle = new Circle(new Red());
Shape greenSquare = new Square(new Green());
redCircle.draw();
greenSquare.draw();
}
}
Red Circle
Green Square