标签:
核心作用:通过代理,控制访问对象的访问。
可以详细控制访问某个(某类)对象的方法,在调用这个前做什么处理,在调用这个方法后做什么处理。(即AOP(面向切面的微观实现))
核心角色:
我们要租房,首先我们会找到中介,中介会带你看房,看好之后和你签订合同,最后交房租,后期房屋有什么问题,直接找中介处理;但是中介只会服务你到签合同,你交房租以及处理房屋问题的时候是和真实房东打交道。
这里:真实的房东就是真实角色;中介就是代理角色;我们抽象出一个出租者就是抽象角色。
/** * Lender 房屋出租者 * @author yangkj*/ public interface Lender { /** * 看房 */ void checkRoom(); /** * 签合同 */ void singContract(); /** * 收房租 */ void collectMoney(); /** * 修理 */ void repari(); }
/** * Agent 房屋中介 * @author yangkj * @version * @since 2016年9月5日 */ public class Agent implements Lender { private Landlord landlord; public Agent(Landlord landlord) { super(); this.landlord = landlord; } @Override public void checkRoom() { System.out.println("中介带着看房"); } @Override public void singContract() { System.out.println("中介和你签合同"); } @Override public void collectMoney() { landlord.collectMoney(); } @Override public void repari() { landlord.repari(); } }
/** * Landlord 真实的房东 * @author yangkj*/ public class Landlord implements Lender{ @Override public void checkRoom() { System.out.println("看房子"); } @Override public void singContract() { System.out.println("签合同"); } @Override public void collectMoney() { System.out.println("房东收房租"); } @Override public void repari() { System.out.println("房屋有什么问题,房东来维修"); } }
/** * Client 客户端 * @author yangkj*/ public class Client { public static void main(String[] args) { Landlord landlord = new Landlord(); Agent agent = new Agent(landlord); agent.checkRoom(); agent.singContract(); agent.collectMoney(); agent.repari(); } }
标签:
原文地址:http://www.cnblogs.com/parryyang/p/5841507.html