装饰者设计模式
来源:互联网 发布:虚拟机与主机网络连接 编辑:程序博客网 时间:2024/05/21 00:18
package 模式练习部分;
public void call();
}
class PhoneTempl implements Phone {
public void call() {
// TODO 自动生成的方法存根
System.out.println("电话的基本模式:打电话");
}
}
// 创建装饰者类出事情况下是什么都不做修饰的
class DectorPhone extends PhoneTempl {
private Phone p;
public DectorPhone (){
}
public DectorPhone(Phone p) {
super();
this.p = p;
}
public void call() {
this.p.call();// 子类重写了父类的方法,当调用子类的方法的时候,调用的是父类的call()方法
}
}
//下面开始具体的修饰功能
class ColorPhone extends DectorPhone{
public ColorPhone(Phone p){
super(p);
}
//对于父类方法的重写
public void call(){
System.out.println("先来一段彩铃!");
super.call();
}
}
//在接完电话以后还有看会儿电视
class WactchTv extends DectorPhone{
//如果父类的构造函数已经有没有参数的了 那么不用集成父类无参数的构造函数
//否则必须继承重写父类中的所有带参数的构造函数
//这样是为了实现子类对于父类对象的赋值初始化
public WactchTv(Phone p) {
super(p);
// TODO 自动生成的构造函数存根
}
public void calll(){
super.call();
System.out.println("打完电话了我要看会儿电视了!");
}
}
public class DectorDemoTest {
public static void main(String[] args) {
PhoneTempl pp = new PhoneTempl();
DectorPhone d = new ColorPhone(pp);
d.call();
System.out.println("彩铃响了,电话来了,电话接了,看电视呀!");
DectorPhone wDectorPhone=new WactchTv(d);
wDectorPhone.call();
}
}
首先创建,手机接口,然后创建最基本功能的手机,也就是只有接电话功能的手机,然后在这个基础上在设计一个装饰类 开始具体的装饰过程,
按照本例中的步骤,下面要做的就是对于具体装饰者的创建,先有彩铃,然后开始接电话,然后在接完电话以后,没有什么其他的事情了,开始看会儿电视休息一下。。。
创建一个接口
创建最基本功能的手机
创建装饰类1
创建装饰类2
在主方法中进行测试
实现装饰者的功能。。
下面附上代码。
interface Phone {public void call();
}
class PhoneTempl implements Phone {
public void call() {
// TODO 自动生成的方法存根
System.out.println("电话的基本模式:打电话");
}
}
// 创建装饰者类出事情况下是什么都不做修饰的
class DectorPhone extends PhoneTempl {
private Phone p;
public DectorPhone (){
}
public DectorPhone(Phone p) {
super();
this.p = p;
}
public void call() {
this.p.call();// 子类重写了父类的方法,当调用子类的方法的时候,调用的是父类的call()方法
}
}
//下面开始具体的修饰功能
class ColorPhone extends DectorPhone{
public ColorPhone(Phone p){
super(p);
}
//对于父类方法的重写
public void call(){
System.out.println("先来一段彩铃!");
super.call();
}
}
//在接完电话以后还有看会儿电视
class WactchTv extends DectorPhone{
//如果父类的构造函数已经有没有参数的了 那么不用集成父类无参数的构造函数
//否则必须继承重写父类中的所有带参数的构造函数
//这样是为了实现子类对于父类对象的赋值初始化
public WactchTv(Phone p) {
super(p);
// TODO 自动生成的构造函数存根
}
public void calll(){
super.call();
System.out.println("打完电话了我要看会儿电视了!");
}
}
public class DectorDemoTest {
public static void main(String[] args) {
PhoneTempl pp = new PhoneTempl();
DectorPhone d = new ColorPhone(pp);
d.call();
System.out.println("彩铃响了,电话来了,电话接了,看电视呀!");
DectorPhone wDectorPhone=new WactchTv(d);
wDectorPhone.call();
}
}
0 0
- 装饰者设计模式
- 设计模式 - 装饰者
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- android与js相互调用(2)基本用法
- ppt实现水滴效果
- 【codevs1031 质数环】回溯法
- Struts2 与Servlet API解耦,耦合的访问方式
- ppt实现水滴效果
- 装饰者设计模式
- 计算机系统分类
- Retrofit初探——POST方式提交JSON数据
- Mysql的优化和架构浅析
- 279. Perfect Squares
- Rdd成员变量Dependency介绍(类型及其如何被初始化)
- tips:js没有块级作用域。
- Android UI开发第二十六篇——Fragment间的通信
- 二阶魔方还原教程