04-代理模式
04代理模式
背景
本博客是照着程杰的《大话设计模式》一书实现的Java代码的版本,再加自己的一点理解
问题
卓贾易追求娇娇的方式是派出自己的好友戴笠
实现该模型的代码逻辑
女孩类
package com.gof.proxy;
/**
* 功能描述
*
* @since 2023-01-17
*/
public class SchoolGirl {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
送礼物接口
package com.gof.proxy;
/**
* 功能描述
*
* @since 2023-01-17
*/
public interface GiveGift {
void givingFlower();
void givingChocolate();
void givingDolly();
}
追求者类
package com.gof.proxy;
/**
* 功能描述
*
* @since 2023-01-17
*/
public class Pursuer implements GiveGift {
private SchoolGirl girl;
public Pursuer(SchoolGirl girl) {
this.girl = girl;
}
@Override
public void givingFlower() {
System.out.println("送花给" + girl.getName());
}
@Override
public void givingChocolate() {
System.out.println("送巧克力给" + girl.getName());
}
@Override
public void givingDolly() {
System.out.println("送洋娃娃给" + girl.getName());
}
}
代理类
package com.gof.proxy;
/**
* 功能描述
*
* @since 2023-01-17
*/
public class Proxy implements GiveGift {
private Pursuer pursuer;
public Proxy(Pursuer pursuer) {
this.pursuer = pursuer;
}
@Override
public void givingFlower() {
pursuer.givingFlower();
}
@Override
public void givingChocolate() {
pursuer.givingChocolate();
}
@Override
public void givingDolly() {
pursuer.givingDolly();
}
}
客户端
package com.gof.proxy;
/**
* 功能描述
*
* @since 2023-01-17
*/
public class Client {
public static void main(String[] args) {
SchoolGirl girl = new SchoolGirl();
girl.setName("jiaojiao");
Pursuer zhuojiayi = new Pursuer(girl);
Proxy daili = new Proxy(zhuojiayi);
daili.givingChocolate();
daili.givingDolly();
daili.givingFlower();
}
}
个人理解
代理类和真实类应该实现了同一个接口,因为代理实现的时候只是调用真实类的实现
简单理解,后续还需要深入