Java接口及静态代理模式练习
1.接口interface 练习,USB与U盘(flash),打印机(printer)
package AbstractExer.computer;
/**
* @version v-1.8.0_131.
* @auther Jack hou Email:256595662@qq.com
* @data 2021/2/23/18:33
* @Description:接口interface 练习,USB与U盘(flash),打印机(printer)
**/
public class Computer {
public static void main(String[] args) {
computer1 computer1=new computer1();
computer1.transferData(new Flash());
computer1.transferData(new Printer());
}
}
class computer1{
public void transferData(USB usb){//USB usb = new Flash();//此处多态父类usb可调用flash重写过得方法
usb.start();
System.out.println("具体传输数据的细节");
usb.stop();
}
}
interface USB{
void start();
void stop();
}
class Flash implements USB{
@Override
public void start() {
System.out.println("U盘开启工作");
}
@Override
public void stop() {
System.out.println("U盘关闭工作");
}
}
class Printer implements USB{
@Override
public void start() {
System.out.println("打印机开启工作");
}
@Override
public void stop() {
System.out.println("打印机结束工作");
}
}
2.静态代理模式练习题:
(1) 网络服务器代理:
package AbstractExer.computer;
/**
* @version v-1.8.0_131.
* @auther Jack hou Email:256595662@qq.com
* @data 2021/2/23/19:57
* @Description:
**/
public class NetWorkTest {
public static void main(String[] args) {
Server server=new Server();
ProxyServer proxyServer = new ProxyServer(new Server());
proxyServer.browse();
}
}
interface NetWork{
public void browse();
}
//被代理类
class Server implements NetWork{
public void browse(){
System.out.println("真实的服务器访问网络");
}
}
//代理类
class ProxyServer implements NetWork{
private NetWork work;
public ProxyServer(NetWork work){
this.work=work;
}
public void check(){
System.out.println("联网之前的检查工作");
}
public void browse(){
check();
work.browse();
}
}
(2)明星与经纪人代理模式练习题:
package AbstractExer.computer;
/**
* @version v-1.8.0_131.
* @auther Jack hou Email:256595662@qq.com
* @data 2021/2/23/20:18
* @Description:
**/
public class StaticProxyTest {
public static void main(String[] args) {
Proxy s = new Proxy(new RealStar());
s.confer();
s.signContract();
s.bookTicket();
s.sing();
s.collectMoney();
}
}
interface Star {
void confer();// 面谈
void signContract();// 签合同
void bookTicket();// 订票
void sing();// 唱歌
void collectMoney();// 收钱
}
//被代理类
class RealStar implements Star {
public void confer() {
}
public void signContract() {
}
public void bookTicket() {
}
public void sing() {
System.out.println("明星:歌唱~~~");
}
public void collectMoney() {
}
}
//代理类
class Proxy implements Star {
private Star real;
public Proxy(Star real) {
this.real = real;
}
public void confer() {
System.out.println("经纪人面谈");
}
public void signContract() {
System.out.println("经纪人签合同");
}
public void bookTicket() {
System.out.println("经纪人订票");
}
public void sing() {
real.sing();
}
public void collectMoney() {
System.out.println("经纪人收钱");
}
}
欢迎点赞评论,谢谢!