簡體   English   中英

在策略模式中,處理共享行為的最佳方法是什么?

[英]In the strategy pattern, what's the best way to deal with shared behaviour?

我已經實現了策略模式-是否有一種聰明的方法來處理下面的function2()和function1()的重復?
IBehaviour接口具有其他不共享功能的成員。

class Behaviour1: IBehaviour
{
    public void DoSomething()
    {
        Function1();
    }
    //other functions of IBehaviour
}

class Behaviour2 : IBehaviour
{

   public void DoSomething()
   { 
       Function2();
       Function1();
   }
   //other functions of IBehaviour
}

class Behaviour3 : IBehaviour
{
    public void DoSomething()
    {
        Function2();
    }
    //other functions of IBehaviour
}

我已經有一堂課來處理這種行為。 然后我意識到不同的情況需要不同的行為,因此在這個主類中,我在運行時創建了一個Behavior對象。 我不願意為Function1和Function2創建另一個類,所以我想知道是否缺少某些東西。

我想到了兩個簡單的選項之一:

  1. 使Behavior3Behavior2繼承。 如果您可以建立明確的“ IS A”關系,或者如果Behavior2相對於Behavior3工作方式發生了變化,則此設計方法確實會在以后給您帶來問題,我只會推薦這種方法。

  2. Function2()移到Behavior2Behavior3可以獨立使用的幫助器類中。

如果更好地重用以補償所需的更多復雜性, IBehavior分為IBehavior1IBehavior2可能是值得的。 然后, Behavior1將實現IBehavior1 ,而Behavior3將實現這兩​​者, IBehavior1 。此方法將遵循相同的原則,具有單一職責和(可能是)接口隔離原則。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM