1. Trang chủ
  2. » Công Nghệ Thông Tin

Uml 2 toolkit phần 7 pps

55 268 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

User-defined stereotypes are often implemented when adapting UML to a specific method or to the application domain that an organization uses. Con- cepts used in the method, or common elements or relationships used in the application domain that are not supported in the standard UML, are usually defined as stereotypes. As noted earlier, stereotypes have been added to the UML to make it easier for the UML designers to answer the question: “Why isn’t the concept X or Y defined in UML?” They can always say: “Define a stereotype for it, and it’s there!” When defining stereotypes, you need to describe: ■■ On which element the user-defined stereotype is based ■■ The new semantics the stereotype adds or refines ■■ One or more examples of how to implement the user-defined stereotype Figure 8.12 shows some examples of the user-defined stereotypes <<time>>, <<semaphore>>, and <<GUI>>. (Note that although UML has other ways to show time, this system required a special stereotype and that these are not standard stereotypes but customizations for this specific model presented in a realistic example.) ■■ The time stereotype applies to associations, specifying that there is a time dependency. A time-stereotyped association must have the multiplicity one-to-many, where the many side is many over time. For example, a shelf might be placed in many bookcases, but only one at a time. ■■ The semaphore stereotype applies to classes. A semaphore class is one whose object guards a resource and allows access to only one or a speci- fied number of users of that resource at a time. A printer should be used only by one thread in the system at a time and, thus, can be guarded by a Printer Queue class with the stereotype <<semaphore>>. The sema- phore semantics indicate that only one thread at a time gains access to the printer queue and, consequently, prevents several threads from con- currently trying to write information to the printer. ■■ The GUI stereotype is a specialization of the boundary stereotype. It has the same functionality and purpose as a boundary class, but concerns only graphical user interfaces (a boundary class also involves any other means of communication with users or other systems). Consequently, a GUI class must be part of a graphical user interface, for example, a win- dow or a message box. The GUI stereotype in Figure 8.12 is an example of a stereotype defined as a specialization of another stereotype (since stereotypes can inherit from each other). For more detail on how to specify a stereotype as a profile element, see the section on profiles later in this chapter. 300 Chapter 8 Figure 8.12 An example of implementing user-defined stereotypes. The Printer Queue class is a semaphore; it connects the Insurance Policy class with the Printer by controlling the access via the Printer Queue. The associations between the controller classes and the Insurance Contracts are stereotyped with time. The Management Window and Sales Window classes are GUI stereotypes. Constraints A constraint is a semantic condition or restriction on elements. Constraints are applied to elements using an expression; one constraint applies to one kind of element. Thus, while a constraint can involve many elements, they must be of the same kind (for example, associations, as in the xor constraint). The con- straints are displayed in braces ({ constraint} ), either directly in the diagrams or separately (typically available through a constraint window in a develop- ment support tool). A constraint can be displayed directly in the diagram next to the view element it constrains. If many elements of the same kind are has refers to 1 0 * * has refers to 0 * 1 * is expressed in an refers to 0 1 1 Insurance Company Insurance Management «GUI» Management Window «Semaphore» Printer Queue Printer Insurance Policy Insurance Contract Customer Change Insurance Contract New Insurance Contract Delete Insurance Contract «GUI» Sales Window * ** * * * * * ** * «Time» «Time» «Time» Extending UML 301 involved in a constraint, the constraint should be displayed near a dashed line that crosses all the elements involved in the constraint (for example, the xor constraint). In UML, a few predefined constraints exist, such as those on gen- eralization sets. Modelers will likely rely on user-defined constraints quite often. The con- straints may be defined directly in a diagram near a view element. The UML tool will typically support the handling of the rule with the related entity. For example, you might need to show that a boss must have a higher salary than his or her assistant, and this could be shown as { person.boss.salary >= per- son.assistant.salary} next to the salary attribute. The rule defined between the braces can be expressed in natural language or any other computer language identified by the modeler. For constraints within UML that execute in the model environment, many recommend the use of the OCL as a specialized lan- guage for expressing constraints. The UML specification uses OCL to express constraints on modeling elements. Examples of UML Constraints UML has some predefined constraints, as were shown throughout the previ- ous chapters of this book. This section reviews some of these to show how con- straints work when applied to different UML model elements. CROSS-REFERENCE For additional standard constraints not shown here, see the time constraints in Chapter 6 and the constraints on generalization covered in Chapter 4. Recognize that for constraints, the power of the construct usually rests in the ability of the modeler to apply his or her own rules wherever needed. There- fore, modelers tend to develop their own constraints. While the UML specifi- cation includes hundreds of constraints, almost all are user defined for the specific entity. In contrast, UML uses stereotypes in a more standard manner as a managed resource; the modeler does not make up so many new stereo- types. Consequently, the number of standard constraints is smaller than the number of standard stereotypes. However, constraints represent a more com- monly used feature to customize the model to fit the circumstances. Constraints for Associations The xor constraint specifies that a set of associations has constraints on their links. The xor constraint is applied where an association connects a single class to a set of other classes. The xor constraint specifies that an object of the single class is connected (linked) to only one of the associated class objects (on the opposite side of the association). For instance, a person can have many (zero or more) insurance contracts, and a company can have many insurance contracts, 302 Chapter 8 as shown in Figure 8.13. The model doesn’t indicate whether an insurance con- tract can be owned by both a person and a company at the same time. To spec- ify that an insurance contract can be owned only by either one person or one company, the xor constraint is used to restrict the associations between Insur- ance Contract and Person and between Insurance Contract and Company. Constraints for Association Roles and Properties The ordered constraint is a standard constraint for association roles. An ordered association specifies that there is an implicit order between the links within the association. Windows are ordered on a screen, for example; one window is on top, one window is at the bottom, and so on. Therefore, the association between the screen and the windows is ordered. The default value for an asso- ciation is unordered, meaning that the links can be in any order. In addition, ordered indicates that the set has only one instance of each value. In contrast, bag used as a constraint indicates that the collection can repeat a value, with seq or sequence indicating a specific order to the bag. The constraint is displayed in braces near the association, as shown in Figure 8.14. Both ordered and unordered constraints can be shown explicitly, though unordered is the default constraint for all associations, and doesn’t have to be specified. The constraint can also apply to all properties, so you can use ordered or sequence to define the nature of an attribute on a class as well. Another constraint typically used on a property and used as a standard in UML is readOnly, which indicates that the element cannot be overwritten. Note that in such cases a Boolean tagged value indicating a true property functions just like a constraint in terms of the model, showing that all instances of the elements with the constraint must have those tag values. Figure 8.13 A Person/Company can have zero or more Insurance Contracts. A contract can be owned by one or many Persons or by one or many Companies. Without the xor constraint one or many Persons and one or many Companies can own the Insurance Contract. If multiplicity were changed at the Person or Company side (to say zero or more), this change would affect the semantics, allowing an Insurance Contract to be owned by no one. Insurance Company 1 0 * Insurance Contract Person 0 * 1 * Company 0 * 1 * {xor} Extending UML 303 Figure 8.14 The constraint { ordered } specifies that there is an explicit order between the links. The exact order can be shown inside the braces as a user-defined constraint, for example, { ordered by increasing time }. Defining Your Own Constraints As noted, user-defined constraints are common. A user-defined constraint is specified for the element to which it applies. The semantic impact—what it means to apply the constraint to an element—is also specified. Constraints are used to limit element semantics in terms of conditions or restrictions of the semantics, and in some cases can represent an advanced feature of your model. Consequently, when you need one of the more advanced constraints (more than just a simple rule), it’s important to evaluate all the effects it might have. As with all types of specifications, it’s useful to give examples of how the constraint can be used. Thus, to specify an advanced constraint, it’s necessary to describe the following: ■■ To which element the user-defined constraint applies ■■ The semantic impact on the element of the user-defined constraint ■■ One or more examples of how to apply the user-defined constraint ■■ How the user-defined constraint can be implemented An example of a more complex user-defined constraint, Singleton, that can be applied to classes is shown in Figure 8.15 and described in the following paragraphs. Insurance Contract Customer 0 * {ordered} 1 * 304 Chapter 8 Figure 8.15 An example with a Singleton class. The Math_Wrapper wraps an old Math library that cannot execute in many simultaneous instances. The Math_Wrapper class has a Singleton constraint. A class with the Singleton constraint has a restriction on the number of objects it may have at the same time. The Singleton class can have only one object at a time. Singleton classes can be used for wrappers where many coex- isting objects can be problematic. For example, if you wrap legacy C code, the code might cause problems when executed in many simultaneous instances. Singleton classes are also used frequently in Web applications to define one object that handles communication with other systems, such as a database connection pool. Singleton classes, typically available throughout the system, can also be used for global configuration objects that should exist only in one instance. A Singleton class can be implemented with a class-scope attribute, which is used as an instance counter. The class constructor increments the class-scope attributes value every time it is called, that is, every time someone creates an object of the class. The destructor, which is in the class, decrements the class- scope attributes value every time it is called—every time someone destroys an object of the class. The default value of the class-scope attribute’s value must be zero because no objects exist before the class; when the class-scope attribute’s value is other than zero or one, an exception is thrown. A variant of this is to provide a class-scope operation to access the Singleton instance. Math_Wrapper {Singleton} Bignum Prim (number : Bignum) Bignum Assign (number : Bignum) Bignum Add (numberA : Bignum, numberB : Bignum) Bignum Mult (numberA : Bignum, numberB : Bignum) Bignum Sqr (number : Bignum) Bignum Pow (number : Bignum) This class has a Singleton constraint. It wraps an old Math library that cannot execute in many simultaneous instances. The Bignum is a class that represent huge numbers. This class is used as a primitive type; there is an implicit dependency between Math_Wrapper and Bignum. Extending UML 305 When the instance counter is incremented to one from zero, this class-scope operation creates the only instance and returns it; and when it is called again, it returns the only existing instance repeatedly. Generally, advanced user-defined constraints are defined separately using a UML tool or as part of a stereotype, but they can also be defined directly in a diagram near a view element. An example of constraints specified directly in a diagram are rules that constrain attributes or links. A Language for Expressing Constraints UML used to include the Object Constraint Language (OCL), a standard way to express constraints with UML that tools could also interpret. Modelers had the option of expressing constraints as strings using natural language or using OCL. Now, OCL receives a first-class definition because it has its own meta- model. Still, users of UML do not have to use OCL. However, for those who use MDA or seek to have their models execute in any way, OCL provides the standard and sanctioned method for articulating constraints on UML models. OCL is no longer defined as part of the basic UML language but rather rep- resents an extension of MOF, providing a real example of extension through the creation of another member of the UML family of languages. Understand- ing how OCL relates to UML illustrates the first class extensions, while also showing the core elements of this constraint language, which is becoming a common way to express rules in a system. OCL Metamodel When the OCL definition was a part of the UML specification, it guaranteed a certain amount of interoperability at a cost of making OCL a less sophisticated construct. Now, OCL attains interoperability through a mapping to the same abstract modeling language, MOF. What is it about OCL that makes it need its own metamodel? OCL provides a good candidate for a full-blown extension. Given that UML is set up to use OCL for machine-readable information, the two languages must operate in a synchronized manner. However, UML does not have as a core a focus on the definition of a constraint language; attaching such features to the UML core would distract from the purpose of the language. The con- straint language has distinct enough requirements that it makes more sense to define it outside UML. Theoretically, one can define the constraint language within UML, but that does not allow for reuse and ties the definition to a lot of elements not central to the expression of constraints. Now, with OCL as a separate construct, language architects have been able to more clearly focus on improving language features such as the handling of collection types. OCL now handles fully nested types, where before OCL 306 Chapter 8 flattened out all types. Certainly, such improvements could have been made within the UML specification; however, these improvements would start to make UML more complex with a difficult combination of tools to wield. Better to have a clear construct for handling constraints outside UML than a set of packages in UML for constraints not as clearly and efficiently designed. A constraint language exists as a pure specification language defined out- side UML for use within UML. OCL only exchanges information about associ- ated elements. These expressions are guaranteed to have no side effects; the constraint language does not change model elements. OCL is used to make expressions that can return a value with a type and has mechanisms to handle such things as pre- and postconditions for an operation. The OCL metamodel has two main packages, a types package that shows the main collections and primitive types available, and an expressions pack- age. The OCL metamodel extends classifier to define the OclMessageType and the OclModelElementType to provide distinct core language types along with the data type elements brought in from the MOF. The expressions package extends Model Element from the infrastructure library of MOF to define the abstract base class for expressions, like OclExpression. As shown in Figure 8.16, the expressions package includes a number of features. This is not the place to go in detail through these elements in the OCL metamodel. The dia- gram, however, illustrates an instance of the language architecture of UML where OCL expressions and types, rather than relating to UML definitions, relate to their own metamodel with interoperability aided by MOF. Figure 8.16 Detail of the OCL expression package. ModelElement This diagram shows the main elements that make up an OCL Expression. This metamodel allows for a rigorous definition of the expression. - name : String OclExpression Classifier IfExp LiteralExp VariableDeclaration - varName : String OclMessageExp ModelPropertyCallExp PropertyCallExp VariableExp LoopExp IterateExpIteratorExp 0 1 0 1 0 1 0 1 0 1 0 1 1 * 0 1 1 1 1 1 Extending UML 307 Basic Structure of OCL Expressions Any UML element that can use an expression can use an OCL expression. OCL expressions relate to a specific place in the UML model, such as a precondition related to a class. OCL can be quickly grasped but has features that take exten- sive training to master. This section shows OCL at a high level. An OCL expression has a context, which is a classifier name as well as the keyword “self,” which is the instance of the classifier. An OCL expression relates to a package, so it can have a namespace. In the example that follows this paragraph, the initial value, shown by init:, for a player in this economic simulation game, equals the total value of the bank times the stake in the bank that the player has at the start of the simulation. Package simulation::banking::person context Player:: value: Integer init: Bank.toalValue * self.bankStake End Package OCL provides syntax to allow a modeler to specify invariants, precondi- tions, postconditions, guards, targets for messages, definitions, derivation rules, initial values, and general constraints using this basic approach with, on the whole, intuitive notation. For a full review of OCL, see the most recent ver- sion of the specification on the OMG Web site (www.omg.org). OCL support for invariants, preconditions, and postconditions replaces the stereotypes for these elements in earlier versions of UML. These constraints, taken together, help support a “design by contract” approach to software development; they are important constraints for UML. UML users are encouraged to use the OCL syntax for expressing these constraints, as shown in the next section. Invariants, Preconditions, and Postconditions Invariant applies to a type. It specifies a property that is preserved over the life- time of an instance of the type. The property is usually some kind of condition that must be valid for the type instance. Some languages, such as Eiffel, have built-in support for invariants, and they can be directly implemented in the final code. The syntax of the value is uninterpreted and usually is not shown in the diagram. For example, a value for an invariant constraint to a color attribute in a class named Car is, in natural language, that the value of the attribute color cannot change during the lifetime of the object or the speed of the car can never be 308 Chapter 8 negative. In OCL, the car speed is expressed as follows, using inv: to show an invariant. The package notation is optional and not shown in this example. Context car inv: CarSpeed >= 0 Precondition applies to an operation. It is a condition that must be true before the operation is invoked. The value is uninterpreted and typically not shown in the diagram. For example, a value for a precondition attached to the opera- tion calculateFinalScore() that takes a person only if that person has completed the game and provides their final score as an integer might be as follows. Context Player::calculateFinalScore():: Integer Pre: self.isComplete = true Postcondition also applies to an operation. It is a condition that must be true after the completion of an operation. The value is uninterpreted and usually not shown in the diagram. For example, a value for a postcondition tag attached to an operation that processes game events for a player and returns the value of the number of choices that should be remaining for the player might be as follows. (Note that the result key word is designed to reference the result of the expression.) Context GameEvent::processPlayerChoices():: Integer Post: result = 0. CROSS-REFERENCE These simple examples show the possible features that OCL can include. For more on OCL, see the specification on the OMG Web site (www.omg.org). Invariants, preconditions, and postconditions are often used together to implement the technique known as programming by contract and, by extension, design by contract. An invariant is a condition that the class implementor guar- antees to be true throughout the execution of the system. A precondition is one that the caller of an operation guarantees to be true before the operation is called, and the postcondition is one that the operation implementor guarantees to be true after the operation has been executed. Should anyone break any of these “contracts,” the system might throw an exception (typically indicating an internal programming error in the system). Making certain that the invari- ants, preconditions, and postconditions have been defined in the model almost always improves the software development effort dramatically. Whether these constraints should be expressed in OCL or in another language depends on the needs of the project. Extending UML 309 [...]... its own model The core UML metamodel now reflects another set of modeling concepts in the MOF, giving the modeling community the ability to supplement UML by creating a cousin of UML This new ability to create another member of the UML family of languages has resulted in the separate specification of a constraint 321 322 Chapter 8 language with OCL, no longer defined in the UML specification The profiles... earlier versions of UML To give UML more precision, a number of companies created variants of “executable UML (xUML) that rely on state machines and an executable action language to generate full systems Some companies, such as Kennedy Carter (www.kc.com), have demonstrated success with xUML on large defense projects In March 20 03, the release of UML 1.5 introduced a definition of UML action semantics... elements of UML The additional model elements in UML, such as those used in sequence diagrams and state machines, rely on constructs from the core These other model elements are part of the UML specification, but they are not part of the UML kernel, or metamodel This fact does not make them any less a part of UML; it just means they are not covered in a section on core elements Figure 8 .20 shows how UML extends... everything in UML, just because the language offers you a feature does not mean that using that feature will bring project success For more on model quality, see Chapter 10 Relevant Changes in UML 2 UML 2 presents the modeler with a rather different extension architecture designed to provide more options, smoother tool support, and clearer definitions for machines No longer does UML use UML to define... (Kabira AS) (For more on xUML, see Executable UML: A Foundation for Model-Driven Architecture by Stephen Mellor and Marc Balcer (Mellor and Balcer, 20 02) ) Although executable UML has worked on some projects, it has not found wide commercial application, especially outside of the defense industry MDA is not simply xUML with new clothing but a broad enough initiative to include both xUML and the folks trying... in MOF and then in UML The Metamodel is made up of metaclasses Profiles Figure 8. 17 High-level UML architecture The core UML elements from the infrastructure library provide the foundation for the UML superstructure Because MOF maps precisely to the infrastructure library, UML also maps to MOF As Figure 8.18 shows, the UML superstructure uses the class package as a set of metaclasses to map to the core... adapt UML to a method, an organization, or a specific application domain Extending UML Profiles extend the UML metamodel as their starting point UML also offers a more elaborate extension mechanism to specify a completely new modeling language, separate from UML but related by a common parent For both of these extension strategies to work, the modeler needs to have a firm grasp of the details in the UML. .. «metaclass» Class - chromosome : Integer Figure 8 .21 Sample stereotype extension 319 320 Chapter 8 «primate» Ape «primate» Human «primate» «primate» chromosome = 48 chromosome = 46 Figure 8 .22 Classes built from a defined stereotype In UML, a modeler applies a profile to his or her model using a dependency relationship with a stereotype of Figure 8 .23 shows an example of how to apply a profile,... at constructs recognizably UML 311 3 12 Chapter 8 «metamodel» Infrastructure Library Core Constructs PrimitiveTypes Basic Abstractions Literals MultiplicityExpressions «metamodel» UML Kernel Generalizations Instances Figure 8.18 Use of the infrastructure library Reviewing the UML Kernel To extend UML constructs, it is worth looking more closely at the kernel package and how UML specifies model elements... extensions into profiles UML still uses its own stereotypes and profiles and will continue to do so, but these should support UML s core aim as a language to model systems that use information technology Constructs, such as constraints or data-modeling tools, will, in the future, reside not in UML but in cousins that also use MOF as the defining modeling language Why does UML 2 need such extension features? . UML than a set of packages in UML for constraints not as clearly and efficiently designed. A constraint language exists as a pure specification language defined out- side UML for use within UML. . 1 1 1 1 1 Extending UML 3 07 Basic Structure of OCL Expressions Any UML element that can use an expression can use an OCL expression. OCL expressions relate to a specific place in the UML model, such. High-level UML architecture. The core UML elements from the infrastructure library provide the founda- tion for the UML superstructure. Because MOF maps precisely to the infra- structure library, UML

Ngày đăng: 09/08/2014, 16:20