java中常用的设计模式-装饰设计模式
来源:互联网 发布:2017大数据就业前景 编辑:程序博客网 时间:2024/05/24 03:23
1. 装饰设计模式
a)当某个类的某个方法不适应当前业务的需要
思路:
》扩展父类的可供扩展的方法,可以使有,但不优
》装饰设计模式(推荐)
开发步骤:
1)写一个普通类或写一个普通类扩展[extends]一个父类
2)写一个需要被包装的实例变量
3)通过构造方式为被包装的实例变量赋值
4)对于不 满足需求的方法,重写父类的相关方法
[可选]5)对于满足需求的方法,直接调用被包装的对象
package cn.sanfy.web.decorator;
import java.io.BufferedReader;
//将BufferedReader进行必包的包装/装饰
public class MyBufferedReader {
private BufferedReader br;
private int no;
public MyBufferedReader(BufferedReader br){
this.br = br;
}
//重写父对象的方法
public String readLine() throws Exception{
String line = null;
line = br.readLine();
if(line!=null){
no++;
line = no + ":" + line;
}
return line;
}
//真接使用父对象的方法
public void close() throws Exception{
br.close();
}
}
package cn.itcast.web.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import cn.sanfy.web.decorator.MyBufferedReader;
public class Test1 {
public static void main(String[] args) throws Exception {
Reader r = new FileReader(new File("d:\\abc.txt"));
BufferedReader br = new BufferedReader(r);
MyBufferedReader mbr = new MyBufferedReader(br);
String line = null;
while((line = mbr.readLine())!=null){
System.out.println(line);
}
mbr.close();
}
}
package cn.sanfy.web.decorator;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
//
public class MyDate {
private Date date;
public MyDate(Date date){
this.date = date;
}
public String toLocaleString(){
String msg = null;
DateFormat df = DateFormat.getDateTimeInstance(
DateFormat.FULL,
DateFormat.MEDIUM,
Locale.CHINA);
msg = df.format(date);
return msg;
}
}
package cn.sanfy.web.test;
import java.util.Date;
import cn.sanfy.web.decorator.MyDate;
public class Test2 {
public static void main(String[] args) {
MyDate date = new MyDate(new Date());
System.out.println(date.toLocaleString());
}
}
- java中常用的设计模式-装饰设计模式
- java常用设计模式(装饰者模式)
- Java装饰设计模式
- Java 装饰设计模式
- Java 装饰设计模式
- java 装饰设计模式
- Java 装饰设计模式
- java 装饰设计模式
- Java装饰设计模式
- Java 装饰设计模式
- Java装饰设计模式
- Java 设计模式 --装饰模式
- Java 设计模式-----装饰模式
- java设计模式-装饰模式
- java设计模式---装饰模式
- java设计模式-装饰模式
- 【Java设计模式】装饰模式
- java设计模式-装饰模式
- 欢迎使用CSDN-markdown编辑器
- linux的nohup命令的用法
- 计算机网络复习——传输层
- 修改hive表location
- Git Patch使用: 生成,导入,解决冲突
- java中常用的设计模式-装饰设计模式
- web根据地址定位
- jQuery的碎碎念
- Mysql的存储引擎的类型,MyISAM&InnoDB等
- python程序语言的安装
- Oracle游标(一)
- VS2010 编译错误 RC1106: invalid option -ologo
- iOS - apple官方ARC文档关键点摘录
- python文件