💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、豆包、星火、月之暗面及文生图、文生视频 广告
## 概述 前辈们把解决问题的方案总结出一个套路.代理设计模式是基于接口的,把需要定义的方法都定义在接口中. ## 静态代理设计模式 ~~~ public class Boy { private String name = "jack"; private Girl girl; //这里可以使用接口,避免换女友需要更改这里. 开闭原则 public Boy(String name) { this.name = name; } public void setGirl(Girl g) { this.girl = g; } public void hungry() { System.out.println("饿了"); girl.cook(); } } ~~~ ~~~ public class Girl { private String name; public Girl(String name) { this.name = name; } public void cook() { System.out.println("女友做饭"); } } ~~~ 调用 ~~~ Boy b = new Boy("jack"); Girl g = new Girl("milan"); b.setGirl(g); b.hungry(); ~~~ ## 更复杂的静态代理 ~~~ public interface ComputerInterface { //卖电脑 public abstract String buyComputer(); //免费维修 public abstract void repair(); } ~~~ ~~~ //被代理类 public class ComputerCompany implements ComputerInterface { @Override public String buyComputer() { return "Y450,3888元"; } @Override public void repair() { System.out.println("免费维修"); } } ~~~ ~~~ //代理类 public class ProxyPerson implements ComputerInterface { //被代理对象 private ComputerInterface lenovo; public ProxyPerson(ComputerInterface lenovo) { this.lenovo = lenovo; } @Override public String buyComputer() { return "鼠标,键盘,电脑包,U盘" + lenovo.buyComputer(); } @Override public void repair() { System.out.println("需要运费"); lenovo.repair(); System.out.println("再给运费"); } } ~~~ ~~~ public static void main(String[] args) { //被代理公司 ComputerCompany lenovo = new ComputerCompany(); //代理对象 ProxyPerson pp = new ProxyPerson(lenovo); //买电脑 String s = pp.buyComputer(); System.out.println(s); pp.repair(); } ~~~