装饰模式
装饰模式(Decorator Pattern)是一种结构型设计模式,它允许在不修改对象自身代码的情况下,动态地为对象添加新的行为。装饰模式通过创建一个装饰类将原始类的实例包裹起来,并在保持类接口不变的前提下,提供额外的功能。
对应实际:当我们使用某个功能的时候,总会发现系统或者库给我们的功能总是过于单一,但是我们需要实现的需求又是多种多样的,所以我们需要对之前的接口进行扩增,做出相应的接口来实现特定的功能
看下面代码(JAVA的)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public class IOss { public static void main(String[] args) { try { FileOutputStream fos = new FileOutputStream("./src/main/java/testIO/test.txt"); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos); dos.writeDouble(3.14159); dos.writeInt(42); dos.writeUTF("Hello, World!"); dos.close(); bos.close(); fos.close(); }catch (FileNotFoundException e ){ e.printStackTrace(); } catch (IOException e) { throw new RuntimeException(e); } } }
|


由此可见,经过一系列包装以后,本来对文件的操作只有普通的读和写
现在有了读/写 字符,数字…………..
在Go中
我觉得这种设计模式更多的是为人服务,目的就简便性
如果我们每次需要检查文件的时候我们肯定都会写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| func IsFileExistOrNot(path string) (bool, error) { _, err := os.Stat(path) if err != nil { if os.IsNotExist(err) { create, err := os.Create(path) if err != nil { return false, err } defer create.Close() return true, nil } return false, err } return true, nil }
|
但是我们不可能每次检查文件的时候都写上这个,不如直接创建一个文件
fs.go
然后在其中写入关于文件的各种操作,只需要传入path,data就可以实现原库中没有的操作
之后有某个需求的时候
1 2 3 4 5 6
| func LoadLog(path string){ b, _ := fs.IsFileExistingOrNot(path) if !b{ panic(..) } }
|
以上。