Spring之静态代理模式
原创
©著作权归作者所有:来自51CTO博客作者小游坦之的原创作品,请联系作者获取转载授权,否则将追究法律责任
案例一:租房
步骤1:接口
package Demo;
public interface Rent {
public void rent();
}
步骤2:房东
package Demo;
//房东手里有房,要租出去
public class Host implements Rent{
public void rent() {
System.out.println("房东要出租房子~");
}
}
步骤3:代理
package Demo;
//代理,帮房东卖房子,还有些附加操作,收点小费,赚个差价
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
public void rent()//你找中介租房子
{
host.rent();//中介去找房东
}
}
步骤4:客户端
package Demo;
public class Client {
public static void main(String[] args) {
Host host = new Host();
Proxy proxy = new Proxy( host);
proxy.rent();
}
}
案例二:增删改查
步骤一:接口:增删改查的方法
public interface Server {
public void add();
public void detele();
public void update();
public void qurey();
}
步骤二:实现类
public class ServerImpl implements Server{
public void add() {
System.out.println("增加了一个用户");
}
public void detele() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("更新了一个用户");
}
public void qurey() {
System.out.println("查询了一个用户");
}
}
步骤三:代理角色,可以实现额外的操作,不影响原来的代码
public class ServerImpl implements Server{
public void add() {
System.out.println("增加了一个用户");
}
public void detele() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("更新了一个用户");
}
public void qurey() {
System.out.println("查询了一个用户");
}
}
步骤四:客户
public class ServerClient {
public static void main(String[] args) {
ServerImpl server = new ServerImpl();
ServerProxy serverProxy =new ServerProxy(server);
serverProxy.detele();
}
}