装饰器模式


package com.oracle.test.shapes;

public abstract class Shape {
    public abstract void draw();
}


package com.oracle.test.shapes;

public class Circle extends Shape{

    @Override
    public void draw() {
        // TODO Auto-generated method stub
        System.out.println("Circle::Draw");
    }

}


package com.oracle.test.shapes;

public class Rectangle extends Shape {

    @Override
    public void draw() {
        // TODO Auto-generated method stub
        System.out.println("Rectangle::Draw");
    }

}


package com.oracle.test.shapes;

public class ShapeDecorator {
    
    private Shape shape;
    public ShapeDecorator(Shape shape) {
        this.shape = shape;
    }
    public void draw() {
        this.shape.draw();
    }
}


package com.oracle.test.shapes;

public class RedShapeDecorator extends ShapeDecorator{

    public RedShapeDecorator(Shape shape) {
        super(shape);
    }

    @Override
    public void draw() {
        // TODO Auto-generated method stub
        super.draw();
        setRedColor();
    }
    
    
    public void setRedColor() {
        System.out.println("Shape::Color Red");
    }
    

}



package com.oracle.test;

import com.oracle.test.shapes.Circle;
import com.oracle.test.shapes.Rectangle;
import com.oracle.test.shapes.RedShapeDecorator;
import com.oracle.test.shapes.Shape;

public class Main {
    public static void main(String[] args) {
        Shape circle = new Circle();
        System.out.println("Common Circle Draw:");
        circle.draw();
        
        
        RedShapeDecorator redCircle = new RedShapeDecorator(circle);
        System.out.println("Red Circle Draw:");
        redCircle.draw();
        
        
        Shape rectangle = new Rectangle(); 
        RedShapeDecorator redRectangle = new RedShapeDecorator(rectangle);
        System.out.println("Red Rectangle Draw:");
        redRectangle.draw();    
    }
}

输出

Common Circle Draw:
Circle::Draw
Red Circle Draw:
Circle::Draw
Shape::Color Red
Red Rectangle Draw:
Rectangle::Draw
Shape::Color Red

你可能感兴趣的:(装饰器模式)