设计模式(十一)代理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/android_bar/article/details/80938680

类结构:

1、抽象服务

public interface Service {

	public void doLogin(String username,String password);
}

2、真实服务

public class RealService implements Service{

	@Override
	public void doLogin(String username,String password) {
		System.out.println("验证用户名、密码!");
	}

}

3、代理服务

public class ProxyService implements Service{
 
	private Service realService=new RealService();
	
	@Override
	public void doLogin(String username,String password) {
		if(!isLogin()){//1.预操作,判断是否已经登陆
			realService.doLogin(username,password);//2.使用登陆服务
			saveLoginState();//3.后操作,保存登陆状态
		}
	}
 
	private boolean isLogin(){//预操作
		System.out.println("查询登陆状态!");
		return false;
	}
	
	private void saveLoginState(){//后操作
		System.out.println("保存登录状态!");
	}
}

4、消费者

public class Customer {

	public static void main(String[] args) {
		Service service=new ProxyService();
		service.doLogin("tom","123456");
	} 

}

5、运行结果

猜你喜欢

转载自blog.csdn.net/android_bar/article/details/80938680