实验2-装饰器,代理模式

1.根据以下类图,采用装饰器模式实现圆形的功能扩展

public interface Shape {
    //画
    public void Draw();
}


public class Circle implements Shape{

    @Override
    public void Draw() {

    }
}


public class CircleEdge extends Decorator{

    public void Draw(){

    }

    public void ColorEdge(){

    }
}

public class CircleFill extends Decorator{
    public void Draw(){

    }

    public void ColorFill(){

    }
}

public class Decorator implements Shape{
    @Override
    public void Draw() {

    }
}

2.在某应用软件中需要记录业务方法的调用日志,在不修改现有业务类的基础上为每一个类提供一个日志记录代理类,在代理类中输出日志,例如在业务方法 method()调用之前输出“方法 method()被调用,调用时间为 2021-11-5 12:10:50”,调用之后如果没有抛异常则输出“方法 method()调用成功”,否则输出“方法 method()调用失败”。在代理类中调用真实业务类的业务方法,使用代理模式设计该日志记录模块的结构,绘制类图并编程模拟实现。

public abstract class AbstractLog {
    public abstract void method();

}

public class BusinessClass extends AbstractLog{
    @Override
    public void method(){
        System.out.println("successful...");
    }
}

public class Client {
    public static void main(String[] args) {
        AbstractLog abstractLog;
        abstractLog = new LoggerProxy();
        abstractLog.method();
    }
}

public class LoggerProxy  extends AbstractLog{
    private BusinessClass businessClass;

    public void before() {
        Date now = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd ',' hh:mm:ss");
        System.out.println("方法method()被调用,调用时间为:" + ft.format(now));
    }
    @Override
    public void method(){
        businessClass = new BusinessClass();
        before();
        try {
            businessClass.method();
            after();
        } catch (Exception e) {
            System.out.println("method() 调用失败");
        }
    }

    public  void after(){
        System.out.println("method() 调用成功");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_54729417/article/details/127954083