1. 程式人生 > 資訊 >漲價!中國移動咪咕視訊鑽石會員價格最新調整:連續包月 20 元、包年 188 元

漲價!中國移動咪咕視訊鑽石會員價格最新調整:連續包月 20 元、包年 188 元

InversionOfControl

https://martinfowler.com/bliki/InversionOfControl.html

中文翻譯,控制反轉。

當你的軟體控制邏輯變得複雜的時候, 控制層適合獨立出來單獨進行管理。

一些框架或者IOC容器,提供了這種能力。

所以確認一個軟體包是庫還是框架, 則控制層是否抽出到軟體包中是一個重要的判斷標誌。

例如

itertools是一個庫,其實若干功能函式的集合,

flask是一個框架,可以獨立執行,負責處理http請求。

原文中對 命令列介面 和 GUI 介面做的對比。

命令列的輸入儲存的控制,都在單體程式中;

但是GUI介面做了分析, 其只對輸入資料的收集負責, 業務程式負責監聽資料收集事件, 並呼叫響應的業務處理程式,包括儲存資料。

這裡的反轉可以理解為, 程式碼不用自己處理控制邏輯, 這些邏輯交由 GUI框架來負責;

即,我們的程式邏輯被框架(或者是自己寫的框架控制邏輯程式碼)控制;

即,程式程式碼從控制的一方,轉變為被控制的一方,這可以理解為反轉。

Inversion of Control is a common phenomenon that you come across when extending frameworks. Indeed it's often seen as a defining characteristic of a framework.

Let's consider a simple example. Imagine I'm writing a program to get some information from a user and I'm using a command line enquiry. I might do it something like this

  #ruby
  puts 'What is your name?'
  name = gets
  process_name(name)
  puts 'What is your quest?'
  quest = gets
  process_quest(quest)

In this interaction, my code is in control: it decides when to ask questions, when to read responses, and when to process those results.

However if I were were to use a windowing system to do something like this, I would do it by configuring a window.

  require 'tk'
  root = TkRoot.new()
  name_label = TkLabel.new() {text "What is Your Name?"}
  name_label.pack
  name = TkEntry.new(root).pack
  name.bind("FocusOut") {process_name(name)}
  quest_label = TkLabel.new() {text "What is Your Quest?"}
  quest_label.pack
  quest = TkEntry.new(root).pack
  quest.bind("FocusOut") {process_quest(quest)}
  Tk.mainloop()

There's a big difference now in the flow of control between these programs - in particular the control of when the process_name and process_quest methods are called. In the command line form I control when these methods are called, but in the window example I don't. Instead I hand control over to the windowing system (with the Tk.mainloop command). It then decides when to call my methods, based on the bindings I made when creating the form. The control is inverted - it calls me rather me calling the framework. This phenomenon is Inversion of Control (also known as the Hollywood Principle - "Don't call us, we'll call you").

框架含有控制邏輯。

業務程式碼只服務具體的業務。

Inversion of Control is a key part of what makes a framework different to a library. A library is essentially a set of functions that you can call, these days usually organized into classes. Each call does some work and returns control to the client.

A framework embodies some abstract design, with more behavior built in. In order to use it you need to insert your behavior into various places in the framework either by subclassing or by plugging in your own classes. The framework's code then calls your code at these points.

Pros

https://en.wikipedia.org/wiki/Inversion_of_control

增加模組性, 使得程式更加具有擴充套件性。

Inversion of control is used to increase modularity of the program and make it extensible,[1] and has applications in object-oriented programming and other programming paradigms. The term was used by Michael Mattsson in a thesis,[2] taken from there[3] by Stefano Mazzocchi and popularized by him in 1999 in a defunct Apache Software Foundation project, Avalon, then further popularized in 2004 by Robert C. Martin and Martin Fowler.

與依賴倒置關係?

https://en.wikipedia.org/wiki/Inversion_of_control

依賴倒置關注高層和底層的依賴解耦, 通過定義一個抽象的中間層;

IoC關注公共邏輯抽取,並提供事件驅動模式行為, 例如事件的callback來處理業務。

The term is related to, but different from, the dependency inversion principle, which concerns itself with decoupling dependencies between high-level and low-level layers through shared abstractions. The general concept is also related to event-driven programming in that it is often implemented using IoC so that the custom code is commonly only concerned with the handling of events, whereas the event loop and dispatch of events/messages is handled by the framework or the runtime environment.

控制反轉

分為三種:

介面定義反轉, 定義在下層模組的介面, 反轉到上層模組, 上層模組依賴此新定義的介面。

流程反轉, 將公共流程定義到上層模組。

依賴建立反轉,程式不自己建立依賴,有框架建立依賴。

Inversion of Control (IoC)

DIP doesn’t tell us how to solve the problem but Inversion of Control defines some way so that we can maintain DIP. It is the thing which you can practically apply on your software development. Lots of definition available for IoC. Here I just try to give asimple definition so that we can easily understand.

What is IoC

IoC helps us to apply DIP. In simple IoC is Inverting the control of something by switching who control. Particular class or another module of the system will be responsible for creation object from outside. Inversion of control means we are changing the control from the normal way.

IoC and DIP

DIP says High level module should not depend on low level module and both should depend on abstraction. IoC is a way that provides abstraction. A way to change the control. IoC gives some ways to implement DIP. If you want to make independent higher level module from the lower level module, then you have to invert the control so that low level module is not controlling interface and creation of the object. Finally, IoC gives some way to invert the control.

Splitting IoC

We can split IoC in the following ways. (Description will be provided later.)

  • Interface Inversion: Inverting interfaces
  • Flow inversion: Invert the flow of control and it is the foundation idea of IoC which is similar to, "Don’t call us, we will call you."
  • Creation Inversion: This is mostly used by developers. We will use it when we go to DI and IoC container.

Fitting Altogether (DIP, IoC and DI)

I am not making full curry here. Just consider the above image how everythingtogether fits. This is the view how all things fittogether. DI is not only the way of Dependency creation that’s why I have used “….” . There are many ways to implement Dependency creation. Here, I am just interested in DI. That’s why I have shown it in the figure and others are doted. At the top is DIP which is a way of designing software. It doesn’t sys how to make independent module. IoC provides some way of applying DPI principle. IoC doesn’t provide specific implementation. It gives some methods so that we can invert the control. If we want to invert control using Binding inversion or dependency creation, then we can achieve it by implementing dependency injection (DI).

依賴倒置

https://juejin.cn/post/6844903487579357191

例如下面例子,定義一個抽象的 車輛 類, 所有車輛繼承此類, 而人只依賴 抽象得車輛類。

本來正常編碼下,肯定會出現上層依賴底層的情況,而依賴倒置原則的應用則改變了它們之間依賴的關係,它引進了抽象。上層依賴於抽象,底層的實現細節也依賴於抽象,所以依賴倒置我們可以理解為依賴關係被改變,如果非常糾結於倒置這個詞,那麼倒置的其實是底層細節,原本它是被上層依賴,現在它倒要依賴與抽象的介面。

控制反轉實現方法

https://www.opensource-techblog.com/inversion-of-control.html

At this point, It’s clear that IOC is a way to achieve a DIP (Dependency Inversion Principle). However, it’s still not clear who will provide the dependencies to the high-level module.

Certain design patterns help in this scenario. They will create and provide the low-level objects (dependencies) to a high-level module. Below is a list of design patterns that do this job.

  1. Dependency Injection
  2. Factory
  3. Service Locator
  4. Observer
  5. Template method

We will see how each of these design patterns helps manage the dependency and allow achieving Inversion of Control in separate blogs.

https://sexywp.com/inversion-of-control-ioc.htm

參考

https://stackoverflow.com/questions/3058/what-is-inversion-of-control

What is Inversion of Control?

If you follow these simple two steps, you have done inversion of control:

  1. Separate what-to-do part from when-to-do part.
  2. Ensure that when part knows as little as possible about what part; and vice versa.

There are several techniques possible for each of these steps based on the technology/language you are using for your implementation.

--

The inversion part of the Inversion of Control (IoC) is the confusing thing; because inversion is the relative term. The best way to understand IoC is to forget about that word!

--

Examples

  • Event Handling. Event Handlers (what-to-do part) -- Raising Events (when-to-do part)
  • Dependency Injection. Code that constructs a dependency (what-to-do part) -- instantiating and injecting that dependency for the clients when needed, which is usually taken care of by the DI tools such as Dagger (when-to-do-part).
  • Interfaces. Component client (when-to-do part) -- Component Interface implementation (what-to-do part)
  • xUnit fixture. Setup and TearDown (what-to-do part) -- xUnit frameworks calls to Setup at the beginning and TearDown at the end (when-to-do part)
  • Template method design pattern. template method when-to-do part -- primitive subclass implementation what-to-do part
  • DLL container methods in COM. DllMain, DllCanUnload, etc (what-to-do part) -- COM/OS (when-to-do part)

Python ABC

IoC第一功能是介面反轉, 需要使用介面功能。

python沒有介面概念, 可以使用 抽象基礎類代替。

https://zhuanlan.zhihu.com/p/89549054

from abc import ABC
from abc import abstractmethod
​
​
class Database(ABC):
    def register(self, host, user, password):
        print("Host : {}".format(host))
        print("User : {}".format(user))
        print("Password : {}".format(password))
        print("Register Success!")
​
    @abstractmethod
    def query(self, *args):
        """
        傳入查詢資料的SQL語句並執行
        """
​
    @staticmethod
    @abstractmethod
    def execute(sql_string):
        """
        執行SQL語句
        """


class Component1(Database):
    def __init__(self, host, user, password):
        self.register(host, user, password)
​
    @staticmethod
    def execute(sql_string):
        print(sql_string)
​
    def query(self, *args):
        sql_string = "SELECT ID FROM db_name"
        self.execute(sql_string)
​
​
class Component2(Database):
    def __init__(self, host, user, password):
        self.register(host, user, password)
​
    @staticmethod
    def execute(sql_string):
        print(sql_string)
​
    def query(self, *args):
        sql_string = "SELECT NAME FROM db_name"
        self.execute(sql_string)
​
comp1 = Component1("00.00.00.00", "abc", "000000")
comp2 = Component2("11.11.11.11", "ABC", "111111")
comp1.query()
comp2.query()
​
出處:http://www.cnblogs.com/lightsong/ 本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線。