设计模式
来源:互联网 发布:java开发外包骗局 编辑:程序博客网 时间:2024/06/06 14:15
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();elsesb.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();}}
0 0
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式~~~~~~~~~~
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- 设计模式
- POJ2154-Daze polya计数法优化
- VERIFIER STOP 00000900: pid 0x???: A heap allocation was leaked.
- linux 逆向
- c++ ActiveX基础1:使用VS2010创建MFC ActiveX工程项目
- 初学android技巧
- 设计模式
- POJ 3308--Paratroopers
- 接下来的几个目标
- 【Hibernate学习】——级联操作
- 法规和国家火炬和交换机
- 和天天见附图一天一天一
- 开发ActiveX控件的实践(1)--用VS2010开发一个简单的TestOcx控件
- 开发ActiveX控件的实践(2)--让控件可以使用DirectShow基类
- hibernate jpa 注解 @Temporal(TemporalType.DATE) 日期注解