1、问题描述
小明家有一个万能遥控器,能够支持多个品牌的电视。每个电视可以执行开机、关机和切换频道的操作,请你使用桥接模式模拟这个操作。
输入示例
6
0 2
1 2
0 4
0 3
1 4
1 3
输出示例
Sony TV is ON
TCL TV is ON
Switching Sony TV channel
Sony TV is OFF
Switching TCL TV channel
TCL TV is OFF
2、桥接模式
它通过将【抽象部分】与【实现部分】分离,使它们可以独⽴变化,从⽽达到降低系统耦合度的⽬的。桥接模式的主要⽬的是通过组合建⽴两个类之间的联系,⽽不是继承的⽅式。
作者认为和代理模式类似,只是目的不同,模式的名称不同,其中有一个类保存了扩展类的引用,实现扩展功能的目的
3、代码
import com.sun.java.accessibility.util.TopLevelWindowListener;import java.util.*;public class Main{public static void main(String[] args){Scanner sc=new Scanner(System.in);int number=sc.nextInt();for(int i=0;i<number;i++){int a=sc.nextInt();int b=sc.nextInt();if(a==0){Television t=new SonyTV();UniversalRemoteControl u=new UniversalRemoteControl(t);if(b==2){u.ControlOn();}else if(b==3){u.ControlOff();}else if(b==4){u.ControlchangeChannel();}}else if(a==1){Television t=new TCLTV();UniversalRemoteControl u=new UniversalRemoteControl(t);if(b==2){u.ControlOn();}else if(b==3){u.ControlOff();}else if(b==4){u.ControlchangeChannel();}}}}
}interface Television{void turnON();void turnOFF();void turnChannel();
}class SonyTV implements Television{@Overridepublic void turnON() {System.out.println("Sony TV is ON");}@Overridepublic void turnOFF() {System.out.println("Sony TV is OFF");}@Overridepublic void turnChannel() {System.out.println("Switching Sony TV channel");}
}class TCLTV implements Television{@Overridepublic void turnON() {System.out.println("TCL TV is ON");}@Overridepublic void turnOFF() {System.out.println("TCL TV is OFF");}@Overridepublic void turnChannel() {System.out.println("Switching TCL TV channel");}
}abstract class RemoteControl{protected Television television;public RemoteControl(Television t){this.television=t;}abstract void ControlOn();abstract void ControlOff();abstract void ControlchangeChannel();}class UniversalRemoteControl extends RemoteControl{public UniversalRemoteControl(Television t){super(t);}@Overridevoid ControlOn() {television.turnON();}@Overridevoid ControlOff() {television.turnOFF();}@Overridevoid ControlchangeChannel() {television.turnChannel();}
}