标签:java buffer 概述 public static can const blog []
装饰设计模式
装饰设计模式概述
装饰模式就是使用被装饰类的一个子类的实例,在客户端将这个子类的实例交给装饰类,是继承的替代方案
优点
使用装饰模式,可以提供比继承更灵活的扩展对象的功能,它可以动态的添加对象的功能,并且可以随意的组合这些功能
缺点
正因为可以随意组合,所以就可能出现一些不合理的逻辑
public class Test { public static void main(String[] args) throws Exception { Phone p = new IPhone(); p.call(); System.out.println("----"); // 需求:先彩铃,后接电话 PhoneDecorator pd = new RingPhoneDecorator(p); pd.call(); System.out.println("----"); // 需求:先接电话,后听音乐 pd = new MusicPhoneDecorator(p); pd.call(); System.out.println("----"); // 需求:先彩铃,再接电话,后听音乐 pd = new RingPhoneDecorator(new MusicPhoneDecorator(p)); pd.call(); } } interface Phone {// 接口 public abstract void call(); } class IPhone implements Phone {// 实现接口 public void call() { System.out.println("call"); } } abstract class PhoneDecorator implements Phone {// 装饰类 private Phone p; public PhoneDecorator(Phone p) { this.p = p; } public void call() { this.p.call(); } } class RingPhoneDecorator extends PhoneDecorator {// 彩铃 public RingPhoneDecorator(Phone p) { super(p); // TODO Auto-generated constructor stub } public void call() { System.out.println("ring"); super.call(); } } class MusicPhoneDecorator extends PhoneDecorator {// 音乐 public MusicPhoneDecorator(Phone p) { super(p); // TODO Auto-generated constructor stub } public void call() { super.call(); System.out.println("music"); } }
组合,装饰模式用于IO流
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Scanner; public class Test { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); Scanner sc = new Scanner(System.in); } }
标签:java buffer 概述 public static can const blog []
原文地址:http://www.cnblogs.com/denggelin/p/6358362.html