国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

Immutable(不可變)集合

2019-11-14 15:50:05
字體:
供稿:網(wǎng)友

不可變集合,顧名思義就是說集合是不可被修改的。集合的數(shù)據(jù)項(xiàng)是在創(chuàng)建的時候提供,并且在整個生命周期中都不可改變。

為什么要用immutable對象?immutable對象有以下的優(yōu)點(diǎn):

  1. 對不可靠的客戶代碼庫來說,它使用安全,可以在未受信任的類庫中安全的使用這些對象
  2. 線程安全的:immutable對象在多線程下安全,沒有競態(tài)條件
  3. 不需要支持可變性, 可以盡量節(jié)省空間和時間的開銷. 所有的不可變集合實(shí)現(xiàn)都比可變集合更加有效的利用內(nèi)存 (analysis)
  4. 可以被使用為一個常量,并且期望在未來也是保持不變的

immutable對象可以很自然地用作常量,因?yàn)樗鼈兲焐褪遣豢勺兊膶τ趇mmutable對象的運(yùn)用來說,它是一個很好的防御編程(defensive PRogramming)的技術(shù)實(shí)踐。

微軟.NET團(tuán)隊(duì)已經(jīng)正式發(fā)布了不可變集合,可以通過Nuget添加,包括了下面的不可變集合:

System.Collections.Immutable.ImmutableArray

System.Collections.Immutable.ImmutableArray<T>

System.Collections.Immutable.ImmutableDictionary

System.Collections.Immutable.ImmutableDictionary<TKey,TValue>

System.Collections.Immutable.ImmutableHashSet

System.Collections.Immutable.ImmutableHashSet<T>

System.Collections.Immutable.ImmutableList

System.Collections.Immutable.ImmutableList<T>

System.Collections.Immutable.ImmutableQueue

System.Collections.Immutable.ImmutableQueue<T>

System.Collections.Immutable.ImmutableSortedDictionary

System.Collections.Immutable.ImmutableSortedDictionary<TKey,TValue>

System.Collections.Immutable.ImmutableSortedSet

System.Collections.Immutable.ImmutableSortedSet<T>

System.Collections.Immutable.ImmutableStack

System.Collections.Immutable.ImmutableStack<T>

MSDN的文檔參考 https://msdn.microsoft.com/zh-cn/library/system.collections.immutable.aspx ,怎么使用呢?我們來看一個例子,假設(shè)你已經(jīng)建立了一個計(jì)費(fèi)系統(tǒng),你需要一個不可變的設(shè)計(jì),在多線程操作的情況下不需要擔(dān)心數(shù)據(jù)損壞。例如,你需要通過一個輔助線程打印數(shù)據(jù)的一個快照,這種方式避免阻塞用戶的編輯操作,允許用戶繼續(xù)編輯而不影響打印。

可變的數(shù)據(jù)模型是這樣:

class Order
{
    public Order()
    {
        Lines = new List<OrderLine>();
    }

    public List<OrderLine> Lines { get; private set; }
}

class OrderLine
{
    public int Quantity { get; set; }
    public decimal UnitPrice { get; set; }
    public float Discount { get; set; }

    public decimal Total
    {
        get
        {
         return Quantity * UnitPrice * (decimal) (1.0f - Discount);
        }
    }
}

下面我們把它轉(zhuǎn)換為不可變的設(shè)計(jì):

class OrderLine
{
    public OrderLine(int quantity, decimal unitPrice, float discount)
    {
        Quantity = quantity;
        UnitPrice = unitPrice;
        Discount = discount;
    }

    public int Quantity { get; private set; }

    public decimal UnitPrice { get; private set; }

    public float Discount { get; private set; }

    public decimal Total
    {
        get
        {
         return Quantity * UnitPrice * (decimal) (1.0f - Discount);
        }
    }
}

這種新設(shè)計(jì)要求您創(chuàng)建一個訂單,每當(dāng)任何屬性值變化創(chuàng)建一個新實(shí)例。您可以通過添加 WithXxx 方法,使您可以更新單個屬性而無需顯式調(diào)用構(gòu)造函數(shù):

class OrderLine
{
    // ...

    public OrderLine WithQuantity(int value)
    {
        return value == Quantity
                ? this
                : new OrderLine(value, UnitPrice, Discount);
    }

    public OrderLine WithUnitPrice(decimal value)
    {
        return value == UnitPrice
                ? this
                : new OrderLine(Quantity, value, Discount);
    }

    public OrderLine WithDiscount(float value)
    {
        return value == Discount
                ? this
                : new OrderLine(Quantity, UnitPrice, value);
    }
}

這使得不可變使用起來比較簡單:

OrderLine apple = new OrderLine(quantity: 1, unitPrice: 2.5m, discount: 0.0f);

OrderLine discountedAppled = apple.WithDiscount(.3f);

現(xiàn)在讓我們看看我們?nèi)绾温鋵?shí)訂單的不變性。Lines 屬性已經(jīng)是只讀的但它指的是可變對象。因?yàn)樗且粋€集合,它可以容易地通過簡單地將它替換 ImmutableList <T>轉(zhuǎn)換:

class Order
{
    public Order(IEnumerable<OrderLine> lines)
    {
        Lines = lines.ToImmutableList();
    }

    public ImmutableList<OrderLine> Lines { get; private set; }

    public Order WithLines(IEnumerable<OrderLine> value)
    {
        return Object.ReferenceEquals(Lines, value)
            ? this
            : new Order(value);
    }
}

這種設(shè)計(jì)有一些有趣的屬性:

• 該構(gòu)造函數(shù)接受 IEnumerable <T>,允許傳遞任何集合中。

• 我們使用 ToImmutableList() 擴(kuò)展方法,將轉(zhuǎn)換為 ImmutableList <OrderLine>。如果該實(shí)例已經(jīng)是不可變的列表,它會簡單地轉(zhuǎn)換而不是創(chuàng)建一個新的集合。

• 該 WithLines() 方法遵循 我們的訂單公約,如果新的列表和當(dāng)前列表是相同的就可以避免創(chuàng)建一個新的實(shí)例。

我們還可以加一些便利的方法來使它更易于更新訂單行:

class Order
{
    //...

    public Order AddLine(OrderLine value)
    {
        return WithLines(Lines.Add(value));
    }

    public Order RemoveLine(OrderLine value)
    {
        return WithLines(Lines.Remove(value));
    }

    public Order ReplaceLine(OrderLine oldValue, OrderLine newValue)
    {
        return oldValue == newValue
                ? this
                : WithLines(Lines.Replace(oldValue, newValue));
    }
}

增補(bǔ)訂單的代碼看起來是這樣子:

OrderLine apple = new OrderLine(quantity: 1, unitPrice: 2.5m, discount: 0.0f);
Order order = new Order(ImmutableList.Create(apple));

OrderLine discountedApple = apple.WithDiscount(discount);
Order discountedOrder = order.ReplaceLine(apple, discountedApple);

這種設(shè)計(jì)的好處是,它盡可能避免了不必要的對象創(chuàng)建。例如,當(dāng)折扣的值等于 0.0 f,即時沒有折扣,,discountedApple 和 discountedOrder 引用現(xiàn)有實(shí)例的蘋果和訂單。

這是因?yàn)?

1.apple.WithDiscount() 將返回蘋果的現(xiàn)有實(shí)例,因?yàn)樾碌恼劭凼窍嗤劭蹖傩缘漠?dāng)前值。

2.order.ReplaceLine() 如果兩個參數(shù)都相同,將返回現(xiàn)有實(shí)例。

我們不變的集合其他操作遵循這種最大化重用。例如,將訂單行添加到 1000 的訂單行的訂單與 1,001 訂單行不會創(chuàng)建整個的新列表。相反,它將重用現(xiàn)有列表一大塊。這是可能的因?yàn)榱斜韮?nèi)部結(jié)構(gòu)是為一棵樹,允許共享不同實(shí)例的節(jié)點(diǎn)。

這里有兩個視頻介紹可變性集合:

 Immutable Collections for .NET

 Inner workings of immutable collections

不可變集合的系列博客推薦:

Exploring the .NET CoreFX Part 9: Immutable Collections and the Builder 

Exploring the .NET CoreFX Part 13: ImmutableList is an AVL Tree

Exploring the .NET CoreFX Part 14: Inside Immutable Collections


發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 汕尾市| 长兴县| 大姚县| 通化县| 余姚市| 阿城市| 贵南县| 乐昌市| 上饶市| 宁河县| 应城市| 康保县| 泰顺县| 龙岩市| 武汉市| 金阳县| 察哈| 和林格尔县| 通道| 格尔木市| 阿克苏市| 伊宁县| 黄陵县| 桂林市| 荣成市| 砀山县| 家居| 扎囊县| 余江县| 宜州市| 榆树市| 罗平县| 诸城市| 东山县| 乌鲁木齐市| 潜江市| 蕲春县| 鹤岗市| 新民市| 留坝县| 启东市|