- Common behavior
- Decoupling
- Restricting behavior
Common behavior:
Decoupling:
Restricting behavior:
The last use case we will discuss can be pretty counterintuitive at first sight. It’s about restricting a type to a specific behavior. Let’s imagine we implement a custom configu-ration package to deal with dynamic configuration. We create a specific container for int configurations via an IntConfig struct that also exposes two methods: Get and Set. Here’s how that code would look:
Now, suppose we receive an IntConfig that holds some specific configuration, such as a threshold. Yet, in our code, we are only interested in retrieving the configuration value, and we want to prevent updating it. How can we enforce that, semantically, this configuration is read-only, if we don’t want to change our configuration package? By creating an abstraction that restricts the behavior to retrieving only a config value:
Then, in our code, we can rely on intConfigGetter instead of the concrete imple-mentation:
In this example, the configuration getter is injected into the NewFoo factory method. It doesn’t impact a client of this function because it can still pass an IntConfig struct as it implements intConfigGetter. Then, we can only read the configuration in the Bar
method, not modify it. Therefore, we can also use interfaces to restrict a type to a spe-cific behavior for various reasons, such as semantics enforcement.
标签:use,code,When,specific,only,behavior,Go,configuration From: https://www.cnblogs.com/zhangzhihui/p/18014593