cool hit counter Design Patterns Cornerstone - Translating UML Relationships into Code_Intefrankly

Design Patterns Cornerstone - Translating UML Relationships into Code


Copyright: This is an original post by the blogger and may not be reproduced without the blogger's permission. https://blog.csdn.net/huyuyang6688/article/details/25076107

1. Succession relations (generalized relations)

Description].The relationship of succession is subcategory( derive (from raw material) kind) succeed parent class( basic kind), or the son interface inheritance interface commercial sector。 i.e. subcategory targets“is a” parent class targets, For example, birds are animals.。

UML diagram].

diagrams:Animal because of parent class,Bird kind、Fish kind、Dog kind respectively, inherited fromAnimal kind, They not only inherit theAnimal of the Common ApproachBreath(), It also expands the methods to suit your own practical needs(Fly() approach、Swim() approach、Run() approach)。

Corresponding code].

    <span style="font-size:18px;">//Animal kind( parent class):
       class Animal
       {
        public void Breath() { }
       }
    //Bird kind、Fish class andDog kind( subcategory):
       class Bird : Animal
      {
        public void Fly() { }
      }
      class Fish : Animal
      {
        public void Swim() { }
      }
      class Dog : Animal
      {
        public void Run() { }
      }</span>

[Draws attention to].

★ instructions subcategory can inherit all parent class in-private properties and methods of the, And it can be expanded to fit the situation( Adding properties or methods), As in the example aboveFly() The method is the bird kind interested in animals kind expansion;

★ Classes can have only single inheritance (a child class can inherit from only one parent class, and a parent class can be inherited by multiple children), and interfaces can have multiple inheritance (a child interface can inherit from multiple parent interfaces).

2. Realization of relationships

【 Description]. The realization of the relationship is kind realize interface The relationship. The following example from Big Talk Design Patterns is quoted to illustrate.

UML diagram].

diagrams: doraemon、 Sun Wukong、 Porky Pig can even change things, But again, because other animals don't have this superpower like the three of them, So it is not possible to add this method directly to the parent classAnimal go back to, And the need to put“ conjure up something” This approach abstracts a method called“ change into something” of interface, When the time comes for animals with such superpowers to( Like the robot cat.、 Sun Wukong、 Pigsy in Arthur Waley's translation) Go ahead and implement this directly interface。

[Corresponding code].

<span style="font-size: 18px;">   //Animal kind、Cat kind、Monkey kind、Pig kind、 (dialect) dragonfly kind The code of the omitted
    interface IChange
    {
        string ChangeThing(string thing);
    }
     class SunWukong:Monkey,IChange//SunWukong inherits from the Monkey class and implements the IChange interface.
    {
         public string ChangeThing(string thing) // Here is the method to implement the interface, note that you can not add the override modifier
        {
            return " I have 72 changes., Can be changed to" + thing;
        }
    }
     class ZhuBajie : Pig, IChange//PigBajie inherits from the Pig class and implements the IChange interface
    {
         public string ChangeThing(string thing) // Here is the method to implement the interface, note that you can not add the override modifier
        {
            return " My old pig has 36 variations, Can be changed to" + thing;
        }
    }</span>

[Draws attention to].

★ classes can implement multiple interfaces, i.e. a class implements multiple interfaces.

★ Because the methods in an interface are used to define a contract for communication between objects, it makes no sense to specify that the methods in an interface are private or protected, so they are public by default, i.e., the interface cannot use modifiers such as new, public, protected, internal, private, etc.

★ In order to distinguish class and interface, interface The names generally start with“I” as the initials( Of course it's fine not to state that)。

(More notes can be found in the Baidu encyclopedia " interface”)

3. Dependencies

【 Description]. If a kindA Need to use another kindB, Or a kindA Responsible for the construction kindB When the instance of, then called kindA depend on kindB, i.e.A kind targets“use a " Class B objects. For example, if a human needs a pen to write, then the relationship is that the human depends on the pen class; and if a machine builds parts, then the machine class depends on the parts class (refer to the simple factory pattern for this example).

UML diagram].

UML diagram of human writing.

UML diagram of machine built parts.

[Corresponding code].

Example 1: Code for People writing (here the dependency is reflected in the way that Pen is a variable in a method in People)

<span style="font-size:18px;">    class People
    {
        public void Write()
        {
            Pen pen=new Pen();
            pen.Write();   
        }
    }
    class Pen
    {
        public void Write(){}
        public void Draw(){}
    }</span>

Example 2: Machine code for building parts (here the dependency is reflected in the way that Part is a return value in a method in Machine)

     class Part // Part class
    {
       private string type;
    }
     class PartA : Part // Part A class (inherits from the part class)
    { }
     class PartB : Part // Part B class (inherits from the part class)
    { }
     class Machine // Machine class (responsibility: selectively produce part A or part B according to requirements)
    {
        public static Part CreatePart(string type)
        {
            Part part = null;
            switch (type)
            {
                case "A":
                    part = new PartA();
                    break;
                case "B":
                    part = new PartB();   
                    break;
            }
            return part;     
        }
    }

[Draws attention to].

★ If A depends on B, the dependency code representation is.

1. B is a variable of the method in A.

2. B is the return value of the method in A.

3. B is a parameter of the method in A.

4. Affiliation

【 Description]. An affiliation is simply a kindA“ know” another kindB at the time of, follow kindA related parties kindB,UML The graph shows the solid line arrow from kindA point towards kindB。 For example, many animals can predict earthquakes、 Natural disasters such as tsunamis, Dogs will bark before a natural disaster、 Rats will come out of their nests and scurry before an earthquake……

UML diagram].

[Corresponding code].

    class Disaster
    { 
        private string name;
        public Disaster(string name)
        {
            this.name = name;
        }
    }
    class Mouse
    {       
       private Disaster disaster;
       public Disaster TheDisaster
       {          
          get{return disaster;}            
          set{this.disaster = value;}
        }
        public void Run(){}    } 
  
    class Dog 
    {     
        private Disaster disaster;    
        public Disaster TheDisaster        
        {          
           get{return disaster;}            
           set{this.disaster = value;}
        }       
        public void Bark(){}    }  
    // Client code  
    static void Main(string[] args)
        {
         Disaster disaster=new Disaster("Typhoon");      
         Mouse mouse=new Mouse();    
         Dog dog=new Dog();
         mouse.TheDisaster=disaster;
         dog.TheDisaster=disaster;
         if(mouse.TheDisaster!=null)
         mouse.Run(); 
         if(dog.TheDisaster!=null)                    
         dog.Bark();
        }

[Draws attention to].

★ The association has a one-way association、 bidirectional correlation、 autochthonous、 Multidimensional correlations, etc.。 The code is reflected as, who kind Associated with another kind Just put it directly in the kind Call that in kind can then (do sth);

★ Distinction between association and dependency.

(1) From the point of view of whether the attributes of the class are increased. The two dependencies that occur kind Neither will add attributes。 One of them. kind As another kind or return value of the method of, Or maybe it's just a variable for some method。 Two of the two that are related kind, One of them. kind Become another kind particular property, And properties are a much tighter coupling, A more permanent holding relationship。 (2) out of relationship life cycle come and see: Dependencies are created only when a method of a class is called, and end with the end of the method. Relationships are created when the class is instantiated, and end when the class is destroyed. Associative relationships have a longer survival period than dependency speaking.

5. Convergence relationships.

【 Description]. in caseA Objects can containB targets, neverthelessB The object does not have to beA Composition of the object part, or soA Object andB The relationship between objects is aggregated, i.e.A targets“contain a " B objects, such as a bicycle containing two wheels, but the two wheels do not necessarily have to be mounted on both bicycles.

UML diagram].

[Corresponding code].

    class Wheel{ }
    class Bicycle
    {
        private Wheel BicycleWheel;
        public Wheel BicycleWheel
        {
            set{BicycleWheel=value;}
            get{return BicycleWheel;}
        }
    }

[Draws attention to].

★ Two of the ordinary associative relationships kind on the same level, And the aggregation relationship between the two kind At a different level, One is. general, One is. part, It's a weak“ own” relations。

★ An A object can contain a B object, but the B object is not a component of the A object. In particular, if A is aggregated into by B, it behaves as if A contains a global object with B, but the B object can be created without the moment of A's creation.

6. Portfolio relationships

[Description]: If a class A object contains a class B object, and the class B object must be a component of the class A object, then the relationship between the class A object and the class B object is an aggregation relationship, that is, the class A object "contain a” B kind targets, For example, a healthy person has two arms and two legs, And these two arms and two legs must belong only to this man。 i.e.A targets“has a " B Object.

UML diagram].

[Corresponding code].

  <span style="font-size:18px;">   class Arm { }
    class Leg { }
    class People
    {
        private Arm myArm;
        private Leg myLeg;
        public People()
        {
            myArm=new Arm();
            myLeg=new Leg();
        }
    }</span>

[Draws attention to].

★ A combination is a stronger relationship than an aggregation relationship. It requires that the ordinary aggregation relation representing general The subject is responsible for representing part of the subject of the life cycle。 The combinatorial relationship is a strong“ own” relations, reflecting the strict part harmony general commercial sector, part harmony general of life cycle unanimous。 in caseA due toB formation, behaveA ContainsB global object of the, furthermoreB The object is in theA Created at the moment of creation。

★ The difference between aggregation and combination: see An Introduction to Aggregation and Combination in UML

Among these relations, the strength of their coupling from strong to weak is. generalization= realize> combine> polymerization> related parties> depend on . Design patterns are like building blocks, and these relationships are like building blocks. The role of design patterns is to combine these relationships to minimize program coupling and optimize the code structure for future requirement changes.

Note that one of the similarities in the code embodiment of the association, aggregation, and combination relationships is that they all have one class as a member of another class. This needs to be understood clearly by heart and not confused.

Everyone, if you have any good examples of instructions or suggestions please give your valuable input, thanks.

【 concentrate: The code for this article is all usedC# to achieve, It may differ from other languages( asjava in subcategory succeed parent class use“class subcategory extends parent class” structure;java in kind realize interface use“class kind implements interface” the structure of the】


Recommended>>
1、Smart cars are a priority for future consumers to purchase
2、Uber Driverless Car Crashes and Kills Man Are Drones Reliable or Not
3、Python basics three main ways to format output strings
4、By collecting data from over 90000 Wifi passwords the following data was compiled
5、Geely BMA architecture under the first sedan the colorful driving technology reached L2 level female drivers look convinced

    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号