装饰模式(Decorator Pattern),强调的是对对象的功能增强。
其中在 JDK 中体现最明显的类就是与 I/O 相关的类,如 BufferedReader、InputStream、OutputStream 及它们的子类。
组合各种类型的字节流,使用
//读取文件 + 可缓存的字节流
new BufferedInputStream(new FileInputStream("D:/c.txt"));
//读取文件 + 直接读取基本类型的字节流
new DataInputStream(new FileInputStream("D:/c.txt"));
IUserDao
public interface IUserDao {
void save();
}
UserDao
public class UserDao implements IUserDao {
@Override
public void save() {
System.out.println("----已经保存数据!----");
}
}
UserDaoTxDecorator
public class UserDaoTxDecorator implements IUserDao {
private IUserDao target;
public UserDaoTxDecorator(IUserDao target){
this.target = target;
}
@Override
public void save() {
System.out.println("开始事务...");
target.save();
System.out.println("提交事务...");
}
}
UserDaoLogDecorator
public class UserDaoLogDecorator implements IUserDao {
private IUserDao target;
public UserDaoLogDecorator(IUserDao target){
this.target = target;
}
@Override
public void save() {
System.out.println("记录开始日志...");
target.save();
System.out.println("记录结束日志...");
}
}
测试
public class App {
public static void main(String[] args) {
//被装饰对象
IUserDao userDao = new UserDao();
//事务装饰
UserDaoTxDecorator txDecorator = new UserDaoTxDecorator(userDao);
//日志装饰
UserDaoLogDecorator logDecorator = new UserDaoLogDecorator(txDecorator);
logDecorator.save();
}
}
评论