Vb. NET Chinese tutorial (2) Composite style

Source: Internet
Author: User
Tags contains implement inheritance integer ord reference
Tutorials | Chinese 1. On the relationship between Whole-part
Recall the traditional software division, often very focused on the writing program (procedure) to deal with some data (data), less concerned about the overall structure of the software (architecture). In today's OO software, data and related programs are combined to encapsulate (encapsulate) in the object. When using objects, the Software division usually treats the object as a black box (Black-box), does not care about the details inside the object, and can focus on the relationship between the objects. The main work of the Software division is to establish the mutual cooperation (collaboration) relationship between the objects, and to arrange the role for the object, but the details inside the object are not important. This allows the software architect to focus on the overall architecture of the software and not into the execution details of the program. This avoids the shortcoming that sees the tree not to see the forest, relaxed the horizon of the Software division, for the Software Multi-Purpose (reusability) and the elasticity (flexibility) think, can create the longevity software!
There are many kinds of common relationships between objects, one of which is whole-part relationships. Like a flower is made up of stamens, petals, and lining leaves, this flower is a "whole" (Whole), and stamens, petals, etc. are the whole "part". Again, the,form1 object on the Windows screen below contains 3 control objects (control) that are part of the Form1. Thus,form1 is a whole, and each control object is a part of the Form1 object.


Figure 1, the Form1 object contains 3 control objects

We can use UML graphics to represent:

Figure 2, Whole-part relationship and inheritance relationship

This diagram includes the Whole-part relationship and the inheritance relationship.
A diamond symbol represents a whole-part relationship; A Form1 object can contain several control objects.
An arrow symbol denotes an inheritance relationship; The control object can be subdivided into several categories.

This paper focuses on the whole-part relationship and establishes the foundation for the composite style. Whole-part relationship can be divided into two types:
The number of "partial" objects is OK. For example, 1 cars contain 1 steering wheels, 1 form objects contain 1 heads (caption) objects, 1 frogs have 4 legs, and so on. Such a determination may be considered a special case of the following "variable" circumstances.
The number of "partial" objects is variable. For example, 1 form objects contain multiple control objects, 1 trees have thousands of leaves, and 1 students report transcripts of each subject and so on. This whole-part relationship usually has to be expressed by a collection (collection) object, such as VB's ArrayList object can be useful.


2. Simple Whole-part Relationship

The most simple whole-part relationship is the other object "containing" (contain). e.g.
S 1 orders listed above are several items purchased
S 1 baseball teams have digital coaches and many players
S students ' transcripts are printed on a number of grades.
S 1 articles are made up of many sentences
The Select Table (menu) On the S screen contains several selections
S 1 papers contain dozens of questions
......

For an example of an order form, there are often multiple purchase items (order lines) listed on orders.


Figure 3, an example of an order

Each purchase item usually includes a product name, purchase quantity, amount, etc. For simplicity's sake, suppose the purchase item contains only the product name and the amount of two items, the whole-part relationship between order and purchase item can be represented by a UML diagram, as shown in the following illustration:


Figure 4, using UML to express simple Whole-part relation

In VB implementation of this UML model, you can use VB ArrayList Collection object to implement (implement) "Order" and "procurement project" between the Whole-part relationship, as shown in the following figure:


Figure 5, using UML to express simple Whole-part relation

Now the VB software division needs to be very accustomed to mastering this whole-part relationship, and often by the collection object to express. Please see the actual VB program, which defines order and orderline two categories:

' Ex01.bas
Imports System.ComponentModel
Imports System.Drawing
Imports system.winforms
Imports System.Collections
'----------------------------------------------------
Class Orderline
Private PName as String
Private Amt as Double
Public Sub New (ByVal na as String, ByVal am as Double)
PName = NA
AMT = AM
End Sub
Public Function Name () as String
Name = PName
End Function
Public Function Amount () as Double
Amount = Amt
End Function
End Class

Class Order
Private OrderID as String
Private lines as ArrayList
Public Sub New (ByVal ID as String)
OrderID = ID
lines = New ArrayList ()
End Sub
Public Sub addline (ByVal ln as orderline)
Lines. ADD (LN)
End Sub
Public Function Amount () as Double
Dim Total as Double = 0
Dim Ln as Orderline
For all Ln in lines
Total = total + ln. Amount ()
Next
Amount = Total
End Function
Public Function Getorderid () as String
Getorderid = OrderID
End Function
End Class
'------------------------------------------------------------------------
Public Class Form1
Inherits System.WinForms.Form

Public Sub New ()
MyBase.New ()

Form1 = Me
' This is required by the Win Form Designer.
InitializeComponent ()
' Todo:add any initialization on the InitializeComponent () call
End Sub
' Form overrides dispose to clean up the component list.
Public Overrides Sub Dispose ()
Mybase.dispose ()
Components. Dispose ()
End Sub
#Region "Windows Form Designer generated code"
......
#End Region
Protected Sub Form1_Click (ByVal sender as Object, ByVal
e as System.EventArgs)
Dim Ord as New order ("Order777")
Dim Pline as Orderline
Pline = New orderline ("Pencil", 88.25)
Ord. AddLine (Pline)

Pline = New orderline ("Ballpen", 110.5)
Ord. AddLine (Pline)
MessageBox.Show (Ord.getorderid + "' s amount =" + str (ORD). Amount ()))
End Sub
End Class

This program outputs:
Order777 ' s cost = 198.75

The lines variable is defined in the order category, and its form arraylist, indicates that lines will represent 1 ArrayList objects, which is essentially a lines variable, containing a reference value, referring to the ArrayList object. In the Order class constructor----New (), the ArrayList object is created and the reference value is deposited in the lines. The procedures are defined as follows:
The amount () program for the order category calculates the total amount for the orders. AddLine () Adds a purchase item to the order. The,ord object in Form1_Click () contains a lines collection object that holds 2 Orderline objects. This expresses the whole-part relationship between the order and the purchase item.
The above procedure is equivalent to-----

' Ex02.bas
Imports System.ComponentModel
Imports System.Drawing
Imports system.winforms
Imports System.Collections
'----------------------------------------------------
Class Order
Class Orderline
Public PName as String
Public Amt as Double
End Class

Private OrderID as String
Private lines as ArrayList

Public Sub New (ByVal ID as String)
OrderID = ID
lines = New ArrayList ()
End Sub
Public Sub AddLine (ByVal PNA as String, ByVal am as Double)
Dim Ln as Orderline
ln = New Orderline ()
Ln.pname = PNA
Ln.amt = AM
Lines. ADD (LN)
End Sub
Public Function Amount () as Double
Dim Total as Double = 0
Dim Ln as Orderline
For all Ln in lines
Total = Total + Ln.amt
Next
Amount = Total
End Function
Public Function Getorderid () as String
Getorderid = OrderID
End Function
End Class
'-----------------------------------------------------
Public Class Form1
Inherits System.WinForms.Form

Public Sub New ()
MyBase.New ()

Form1 = Me
' This is required by the Win Form Designer.
InitializeComponent ()
' Todo:add any initialization on the InitializeComponent () call
End Sub
' Form overrides dispose to clean up the component list.
Public Overrides Sub Dispose ()
Mybase.dispose ()
Components. Dispose ()
End Sub
#Region "Windows Form Designer generated code"
......
#End Region
Protected Sub Form1_Click (ByVal sender as Object, ByVal e as System.EventArgs)
Dim Ord as New order ("Order777")
Ord. AddLine ("Pencil", 88.25)
Ord. AddLine ("Ballpen", 110.5)
MessageBox.Show (Ord.getorderid + "' s amount =" + str (ORD). Amount ()))
End Sub
End Class

This program outputs:
Order777 ' s cost = 198.75




3. Recursive Whole-part Relationship

Whole-part relationships contain other whole-part relationships and allow multi-level whole-part relationships, collectively known as recursive whole-part relationships. This kind of relationship is common in nature, for example, the leaves are part of a tree, but the leaves are a whole, which contains the "part" objects of the veins, chlorophyll and so on.


Fig. 6, multi-level whole-part relationship in nature

In the business world, the most typical example is the "Object Structure table" (Bill of material, BOM), as follows:


Figure 7, Whole-part Relationship of enterprise material table (BOM)

At first glance, these structures seem complex, but from these graphs you can see that these objects can be grouped into two categories depending on their role:

1. Leaf object. As in the "white" category in the above figure, they do not have a whole role and have only part roles. This is known as the "Basic component" (primitive component).

2. Composite object. As objects in the "gray" category above, they have a whole role, and may also have part roles. This is known as "composite Assembly" (composite component).

For this, only two categories of ──leaf and composite categories can be defined.




4. Implement composite style with VB

The recursive Whole-part relationship is very common and is the usual skill of software designers. Thus, in Gamma's "Design Patterns" book (note 1), it is also included as an important "style" (pattern) of 1. The style chart of the book is as follows:


Figure 8, composite style

It is recommended that we define the Add (), Remove () and Getchild () three basic, Overridable, and other programs. Experts regard this notation as a style, meaning that this is the ideal expression that experts think. Now, to actually express the above BOM structure in accordance with this style, you must define the following categories:
The U part category-----corresponds to Component
U piecepart category-----corresponding to the leaf
U assemblypart category-----corresponds to composite

Then the implementation of the VB program, as follows:
' Ex03.bas
Imports System.ComponentModel
Imports System.Drawing
Imports system.winforms
Imports System.Collections
'----------------------------------------------------
Interface IPART
Sub Add (ByVal p as IPART)
Function Getchild (ByVal N as Integer) as IPART
Function cost () as Double
Function Name () as String
End Interface

Class part
Private PName as String
Protected Sub New (ByVal na as String)
PName = NA
End Sub
Protected Function getName () as String
GetName = PName
End Function
End Class

Class Piecepart
Implements IPART
Inherits part
Private Pcost as Double

Public Sub New (ByVal na as String, ByVal C as Double)
MyBase.New (NA)
Pcost = C
End Sub
Public Sub Add (ByVal p as IPART) Implements Ipart.add
MessageBox.Show ("Parts do not have subparts")
End Sub
Public Function Subpart (ByVal N as Integer) as IPART Implements Ipart.getchild
Subpart = Nothing
End Function
Public Function cost () as Double Implements ipart.cost
Cost = Pcost
End Function
Public Function Name () as String Implements Ipart.name
Name = Mybase.getname ()
End Function
End Class

Class Assemblypart
Implements IPART
Inherits part

Private Children as ArrayList

Public Sub New (ByVal na as String)
MyBase.New (NA)
Children = New ArrayList ()
End Sub
Public Sub Add (ByVal p as IPART) Implements Ipart.add
Children. ADD (P)
End Sub
Public Function Subpart (ByVal N as Integer) as IPART Implements Ipart.getchild
Dim obj as Object
obj = children. Item (N)
Subpart = CType (obj, IPART)
End Function
Public Function cost () as Double Implements ipart.cost
Dim Sum as Double
Dim PS as Ipart
sum = 0
For each PS in children
sum = SUM + PS. Cost ()
Next
Cost = Sum
End Function
Public Function Name () as String Implements Ipart.name
Name = Mybase.getname ()
End Function
End Class
'-----------------------------------------------------
Public Class Form1
Inherits System.WinForms.Form
Public Sub New ()
MyBase.New ()
Form1 = Me
' This is required by the Win Form Designer.
InitializeComponent ()
' Todo:add any initialization on the InitializeComponent () call
End Sub
' Form overrides dispose to clean up the component list.
Public Overrides Sub Dispose ()
Mybase.dispose ()
Components. Dispose ()
End Sub
#Region "Windows Form Designer generated code"
......
#End Region
Protected Sub Form1_Click (ByVal sender as Object, ByVal
e as System.EventArgs)
Dim aly1, Aly2, p1, p2 as Ipart
Dim PS as Ipart

Aly1 = New Assemblypart ("bulb")
P1 = New Piecepart ("Body", 88.25)
Aly1. Add (p1)
P1 = New Piecepart ("Head", 100.5)
Aly1. Add (p1)

Aly2 = New Assemblypart ("Light")
Aly2. ADD (ALY1)
P1 = New Piecepart ("cover", 10)
Aly2. Add (p1)
MessageBox.Show (aly2. Name () + "' s cost =" + str (aly2). Cost ()))

P1 = Aly2. Getchild (0)
MessageBox.Show (P1. Name + "' s cost =" + str (p1). Cost ()))

P2 = aly2. Getchild (1)
MessageBox.Show (P2.name + "' s cost =" + str (p2). Cost ()))

P2 = p1. Getchild (0)
MessageBox.Show (P2. Name + "' s cost =" + str (p2). Cost ()))
End Sub
End Class

This program output: Light ' s cost = 198.75
Bulb ' s cost = 188.75
Cover ' s cost = 10
Body ' s cost = 88.25

Piecepart represents the lowest level of basic objects. The Assemblypart represents intermediate-level semi-finished object components, or represents the finished product. Part is an abstract class that defines the common parts of the Piecepart and Assemblypart categories (including attributes and behavior) for Piecepart and Assemblypart subcategories to inherit. In addition, it is important to provide an interface IPART to the client to encapsulate the part, Piecepart, and Assemblypart categories to create resilient adjustment space for the "s, Piecepart, and Assemblypart categories."
The Form1_Click () program establishes the object structure table for "Car headlights":


Figure 8, VB program born object diagram

P1 = Aly2. Getchild (0) takes out "bulb" small object, and by P1 represents this small object. P2 = p1. Getchild (0) Take out "lamp cap" small object, and by P2 representative. According to the above style, we can express the infinite level recursive whole-part relation.
In order for the software to survive continuously, special attention must be paid to the organization of the software and its overall architecture (architecture). So, when designing software, you must focus on the mutual cooperation between objects. Once the ideal relationship is established, the objects can be communicated to each other. For example, the,form1 object transmits the cost message to the Aly2 object,aly2 object to pass the cost message to the contained objects, based on the relationship established by the ArrayList object. When each small object returns its cost amount,aly2 it is then transferred back to the Form1 object and then displayed on the window screen. At the moment, I believe you have a better understanding of whole-part relationship, use the ArrayList collection categories to express, and will use VB to implement the style, to create a better software.

[Note 1] Erich gamma,design patterns:elements of reusable object-oriented Software, Addition-wesley, 1995.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.