设计模式

1、单例模式:

package javaBase;

public class Single {
	private Single(){}  //私有化构造函数
	private static Single s = new Single();//创建私有并静态的本类对象
	public static Single getInstance(){//公共并静态的方法,返回该对象
		return s;
	}
	
}

package designMode;

public class Single {
	//懒汉式:
	private Single(){};
	private static Single instance = null;
	public static Single getInstance(){
		if(instance ==null){
			synchronized (Single.class) {
				if(instance ==null){
					instance = new Single();
				}
			}
		}
		 return instance;
	}
}


2、装饰设计模式:

装饰类和被装饰类通常是都属于同一个体系中的,因为它们的功能是相同的,只是更强而已。

装饰模式比继承要灵活,避免了继承的臃肿,也降低了类与类之间的关系。

继承的逻辑是a属于b

装饰的逻辑是a里面有b   

package javaBase.io;
import java.io.*;
//自定义一个BufferedReader来增强FileReader的功能,实现readLine()
//装饰设计模式,通常会通过构造函数接收被装饰的对象,并基于该对象提供增强的功能
class MyBufferedReader {
	private FileReader fr;
	public MyBufferedReader(FileReader fr){//构造方法
		this.fr = fr;
	}
	public String myReadLine() throws IOException{
		
		//定义一个临时容器来存放一行的数据,源码使用字符数组
		//这里用StringBuilder(可变字符序列,非线程安全),最终都是要转成String返回的
		StringBuilder sb = new StringBuilder();
		int ch = 0;
		while((ch = fr.read())!= -1){
			if(ch == '\r')
				continue;
			if(ch =='\n')
				return sb.toString();
			else
				sb.append((char)ch);
		}
		if(sb.length()!=0)//最后一行若是没有换行符的处理
			return sb.toString();
		return null;
	}
	public void myClose() throws IOException{
		fr.close();
	}
}

class MyReadLine{
		public static void main(String[] args) throws IOException {
			MyBufferedReader mybr = new MyBufferedReader(new FileReader("original.java"));
			String str = null;
			while((str = mybr.myReadLine())!=null){
				System.out.println(str);
			}
			mybr.myClose();
		}
	
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值