黑马程序员+Java基础中的设计模式

来源:互联网 发布:centos mail 发送邮件 编辑:程序博客网 时间:2024/06/05 18:02
------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流! -------

在Java基础学习过程中,感觉设计模式相关知识点有些乱,对此用思维导图及代码做了一些总结和概括,由于本人水平有限,可能会有不完善或错误的地方,敬请指正,谢谢!


图1 设计模式

在Java基础学习过程中介绍了单例设计模式及装饰设计模式。以下用思维导图及代码作了一些介绍。


图2 单例设计模式


图3  装饰模式

懒汉式单例实例:

 class Single{ private static Single s= null;//静态私有成变量 private Single(){};//私有构造方法 public static Single getInstance(){ if(s == null){ synchronized(Single.class){//同步 if(s==null){ s = new Single(); } } }return  s;}

俄汉式单力设计模式实例:
public class Singleton1 {      //私有的默认构造子      private Singleton1() {}      //已经自行实例化       private static final Singleton1 single = new Singleton1();      //静态工厂方法       public static Singleton1 getInstance() {          return single;      }
修饰设计模式实例
public class MyBuffer { private InputStream is; private byte[] b = new byte[1024]; int pos=0,count=0; MyBuffer(InputStream is){ this.is = is; } //每次从缓冲区中读取一个字节流,返回int型是为了避免连续出现8个1,与条件冲突,用int, //4个字节,前面补0,(将字节和255相与) public int myRead() throws IOException{ if(count == 0){ count = is.read(b);//将文件中的字符流对象存到指定缓冲区 if(count < 0) return -1; pos = 0; byte by = b[pos]; pos++; count--;  return by&255;} else if(count > 0){ byte by = b[pos]; pos++; count--;  return by&255; } return -1; } public void myClose() throws IOException{ is.close(); }}

public class TestMyBuffer {public static void main(String[] args) {// TODO 自动生成的方法存根FileInputStream fis=null;FileOutputStream fos=null;MyBuffer mb=null;try {fis=new FileInputStream("d:\\1.jpg");mb = new MyBuffer(fis);fos=new FileOutputStream("d:\\2.jpg");while(true){int b =mb.myRead();if(b==-1)break;fos.write(b);} } catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}finally{try {mb.myClose();} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}try {fos.close();} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}  }}






0 0