java多态(接口与实现)之静态代理

//废话不多说,直接上代码
public class Test {
     
    static interface Subject{
     
        void sayHi();
        void sayHello();
    }

    static class SubjectImpl implements Subject{
     

        @Override
        public void sayHi() {
            System.out.println("hi");
        }

        @Override
        public void sayHello() {
            System.out.println("hello");
        }
    }

    static class SubjectImplProxy implements Subject{
     
        private Subject target;

        public SubjectImplProxy(Subject target) {
            this.target=target;
        }

        @Override
        public void sayHi() {
            System.out.print("say:");
            target.sayHi();
        }

        @Override
        public void sayHello() {
            System.out.print("say:");
            target.sayHello();
        }
    }

    public static void main(String[] args) {
        Subject subject=new SubjectImpl();
        Subject subjectProxy=new SubjectImplProxy(subject);
        subjectProxy.sayHi();
        subjectProxy.sayHello();
    }
}
//直接说main方法的调用过程:
subjectProxy.sayHi()调用SubjectImplProxy这个实现类的sayHi()方法,这个时候SubjectImplProxy类中的变量target已经被实例化,实例化的实现类为SubjectImpl ,所以target.sayHi()这个方法调用SubjectImpl 这个实现类的sayHi()方法。
打印结果:say:hi
        say:hello

你可能感兴趣的:(java,多态)