Constraints are applied to elements using an expression; one constraint applies to one kind ofelement.. Thus, to specify an advanced constraint, it’s necessary to describe the following:
Trang 1User-defined stereotypes are often implemented when adapting UML to aspecific method or to the application domain that an organization uses Con-cepts used in the method, or common elements or relationships used in theapplication domain that are not supported in the standard UML, are usuallydefined as stereotypes As noted earlier, stereotypes have been added to theUML to make it easier for the UML designers to answer the question: “Whyisn’t the concept X or Y defined in UML?” They can always say: “Define astereotype 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 stereotypeFigure 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 arealistic example.)
■■ The time stereotype applies to associations, specifying that there is a time
dependency A time-stereotyped association must have the multiplicityone-to-many, where the many side is many over time For example, ashelf 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 fied number of users of that resource at a time A printer should be usedonly by one thread in the system at a time and, thus, can be guarded by
speci-a Printer Queue clspeci-ass with the stereotype <<semspeci-aphore>> The semspeci-a-phore semantics indicate that only one thread at a time gains access tothe printer queue and, consequently, prevents several threads from con-currently trying to write information to the printer
sema-■■ The GUI stereotype is a specialization of the boundary stereotype It has
the same functionality and purpose as a boundary class, but concernsonly graphical user interfaces (a boundary class also involves any othermeans of communication with users or other systems) Consequently, aGUI 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 (sincestereotypes can inherit from each other)
For more detail on how to specify a stereotype as a profile element, see thesection on profiles later in this chapter
Trang 2Figure 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 ofelement Thus, while a constraint can involve many elements, they must be ofthe 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 ment support tool) A constraint can be displayed directly in the diagram next
develop-to the view element it constrains If many elements of the same kind are
has refers to
Insurance Management
«GUI»
Management Window
Customer
Change Insurance Contract
New Insurance Contract
Delete Insurance Contract
«GUI»
Sales Window
Trang 3involved in a constraint, the constraint should be displayed near a dashed linethat crosses all the elements involved in the constraint (for example, the xorconstraint) 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 straints may be defined directly in a diagram near a view element The UMLtool will typically support the handling of the rule with the related entity Forexample, you might need to show that a boss must have a higher salary thanhis 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 thebraces can be expressed in natural language or any other computer languageidentified by the modeler For constraints within UML that execute in themodel environment, many recommend the use of the OCL as a specialized lan-guage for expressing constraints The UML specification uses OCL to expressconstraints on modeling elements
con-Examples of UML Constraints
UML has some predefined constraints, as were shown throughout the ous chapters of this book This section reviews some of these to show how con-straints work when applied to different UML model elements
previ-C R O S S - R E F E R E N previ-C E 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 theability 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 thespecific entity In contrast, UML uses stereotypes in a more standard manner
as a managed resource; the modeler does not make up so many new types Consequently, the number of standard constraints is smaller than thenumber of standard stereotypes However, constraints represent a more com-monly used feature to customize the model to fit the circumstances
stereo-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 singleclass is connected (linked) to only one of the associated class objects (on theopposite side of the association) For instance, a person can have many (zero ormore) insurance contracts, and a company can have many insurance contracts,
Trang 4as shown in Figure 8.13 The model doesn’t indicate whether an insurance 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 onecompany, the xor constraint is used to restrict the associations between Insur-ance Contract and Person and between Insurance Contract and Company.
con-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 theassociation Windows are ordered on a screen, for example; one window is ontop, one window is at the bottom, and so on Therefore, the associationbetween 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 andunordered constraints can be shown explicitly, though unordered is thedefault constraint for all associations, and doesn’t have to be specified Theconstraint 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 functionsjust like a constraint in terms of the model, showing that all instances of theelements 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.
Trang 5Figure 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 isspecified for the element to which it applies The semantic impact—what itmeans to apply the constraint to an element—is also specified Constraints areused to limit element semantics in terms of conditions or restrictions of thesemantics, and in some cases can represent an advanced feature of yourmodel 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 mighthave As with all types of specifications, it’s useful to give examples of how theconstraint 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 followingparagraphs
Trang 6Figure 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 ofobjects it may have at the same time The Singleton class can have only oneobject 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, thecode might cause problems when executed in many simultaneous instances.Singleton classes are also used frequently in Web applications to define oneobject that handles communication with other systems, such as a databaseconnection pool Singleton classes, typically available throughout the system,can also be used for global configuration objects that should exist only in oneinstance
A Singleton class can be implemented with a class-scope attribute, which isused as an instance counter The class constructor increments the class-scopeattributes value every time it is called, that is, every time someone creates anobject 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 anobject 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-scopeattribute’s value is other than zero or one, an exception is thrown A variant ofthis 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.
Trang 7When the instance counter is incremented to one from zero, this class-scopeoperation 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 aUML tool or as part of a stereotype, but they can also be defined directly in adiagram near a view element An example of constraints specified directly in adiagram 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 hadthe option of expressing constraints as strings using natural language or usingOCL 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 whouse MDA or seek to have their models execute in any way, OCL provides thestandard 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 throughthe creation of another member of the UML family of languages Understand-ing how OCL relates to UML illustrates the first class extensions, while alsoshowing the core elements of this constraint language, which is becoming acommon way to express rules in a system
OCL Metamodel
When the OCL definition was a part of the UML specification, it guaranteed acertain amount of interoperability at a cost of making OCL a less sophisticatedconstruct Now, OCL attains interoperability through a mapping to the sameabstract modeling language, MOF What is it about OCL that makes it need itsown 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 languagesmust operate in a synchronized manner However, UML does not have as acore 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 straint language has distinct enough requirements that it makes more sense todefine it outside UML Theoretically, one can define the constraint languagewithin UML, but that does not allow for reuse and ties the definition to a lot ofelements not central to the expression of constraints
con-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
Trang 8flattened out all types Certainly, such improvements could have been madewithin the UML specification; however, these improvements would start tomake 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 ofpackages in UML for constraints not as clearly and efficiently designed
A constraint language exists as a pure specification language defined side UML for use within UML OCL only exchanges information about associ-ated elements These expressions are guaranteed to have no side effects; theconstraint language does not change model elements OCL is used to makeexpressions that can return a value with a type and has mechanisms to handlesuch things as pre- and postconditions for an operation
out-The OCL metamodel has two main packages, a types package that showsthe main collections and primitive types available, and an expressions pack-age The OCL metamodel extends classifier to define the OclMessageType andthe OclModelElementType to provide distinct core language types along withthe data type elements brought in from the MOF The expressions packageextends Model Element from the infrastructure library of MOF to define theabstract base class for expressions, like OclExpression As shown in Figure8.16, the expressions package includes a number of features This is not theplace to go in detail through these elements in the OCL metamodel The dia-gram, however, illustrates an instance of the language architecture of UMLwhere 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.
0 1
0 1
0 1
0 1 0 1
0 1
1 *
0 1 1
1
1
1
Trang 9Basic Structure of OCL Expressions
Any UML element that can use an expression can use an OCL expression OCLexpressions relate to a specific place in the UML model, such as a preconditionrelated 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 thekeyword “self,” which is the instance of the classifier An OCL expressionrelates to a package, so it can have a namespace In the example that followsthis paragraph, the initial value, shown by init:, for a player in this economicsimulation game, equals the total value of the bank times the stake in the bankthat 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, tions, postconditions, guards, targets for messages, definitions, derivationrules, initial values, and general constraints using this basic approach with, onthe 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 supportfor invariants, preconditions, and postconditions replaces the stereotypes forthese elements in earlier versions of UML These constraints, taken together,help support a “design by contract” approach to software development; theyare important constraints for UML UML users are encouraged to use the OCLsyntax for expressing these constraints, as shown in the next section
precondi-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 conditionthat must be valid for the type instance Some languages, such as Eiffel, havebuilt-in support for invariants, and they can be directly implemented in thefinal 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 classnamed Car is, in natural language, that the value of the attribute color cannotchange during the lifetime of the object or the speed of the car can never be
Trang 10negative In OCL, the car speed is expressed as follows, using inv: to show aninvariant 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 usuallynot shown in the diagram For example, a value for a postcondition tagattached to an operation that processes game events for a player and returnsthe 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.
C R O S S - R E F E R E N C E 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 ofthese “contracts,” the system might throw an exception (typically indicating
an internal programming error in the system) Making certain that the ants, preconditions, and postconditions have been defined in the modelalmost always improves the software development effort dramatically.Whether these constraints should be expressed in OCL or in another languagedepends on the needs of the project
Trang 11invari-Language Architecture and Kernel Overview
To implement user-defined extensions, it is important to familiarize yourselfwith the UML’s semantics or at least the core semantics Although most of thisbook focuses on the UML superstructure, this section focuses on the UMLinfrastructure and the language kernel This structure carefully defines exten-sion mechanisms, making UML a modeling language that essentially canextend itself Both syntax—which indicates the form for stating information—and semantics—which indicate the content of a statement—are formallydefined
As an aid, this section provides a simplified description of the main UMLelements Again, we recommend that you have a basic knowledge of the coresemantics before you create your own stereotypes or profiles This section alsohelps you to understand the underlying model of the UML and what it meansfor the modeler
High-Level Language Constructs
As shown in Figure 8.17, the language architecture starts from the ture library package, which contains two packages; a core, which has the mainlanguage elements, and profiles, which define the ways to extend languageelements, making it easier for tools to support these features From such asmall seed, a number of language constructs grow with automated support.The MOF uses the infrastructure library as a metamodel, or a model used todefine other models The MOF represents a special type of metamodel used todefine other metamodels, what you could theoretically term a meta-metamodel.The UML metamodel then relies on MOF
infrastruc-What does MOF supply UML? MOF provides the rules for the reflectiveinterfaces in a reflection package, as well as rules for the exchange of XML def-initions of a model using XML Metadata Interchange (XMI) Thus, MOF makes
it easier to share models between different development support tools as itdefines the rules for automated querying of model elements and the exchange
of information This architecture also defines different compliance points, sotool vendors can easily identify the features they support A “basic” packagesets out a minimum expected level of compliance for tool vendors Theemphasis on having compliance checked by XMI means that UML can bedefined automatically without references to the visual information For map-ping to the visual information, UML has a diagram interchange specification
Trang 12Figure 8.17 High-level UML architecture.
The core UML elements from the infrastructure library provide the tion for the UML superstructure Because MOF maps precisely to the infra-structure library, UML also maps to MOF As Figure 8.18 shows, the UMLsuperstructure uses the class package as a set of metaclasses to map to the coreconcepts of the metamodel The other top-level packages use the class package
founda-to provide the language definition Within the class package, the kernel age represents the core elements of UML The kernel combines the many sep-arate packages found in the infrastructure library, designed atomically toallow for reuse and flexibility, into a coherent modeling language designed tomodel software This complex exercise in object-oriented modeling hasevolved to provide more abstract modeling mechanisms, while at the sametime providing a clearer definition of the core of UML itself Finally, at thatpoint, we arrive at constructs recognizably UML
pack-«metamodel»
Infracture Library Core
Classes from the core represent
metaclasses, used in MOF and
then in UML The Metamodel
Trang 13Figure 8.18 Use of the infrastructure library.
Reviewing the UML Kernel
To extend UML constructs, it is worth looking more closely at the kernel age and how UML specifies model elements As mentioned, the kernelincludes the core of UML so it represents a large selection of classes in onepackage To organize these classes, the specification breaks their relationshipsdown into a number of class diagrams, rather than packages At the very root
pack-of the kernel is a class called element, which is used in most pack-of these diagrams
«metamodel»
Infrastructure Library Core
Kernel
Trang 14An element is the abstract base class for UML It acts as an anchor to which
you can attach a number of mechanisms The kernel extends the base class ment in a number of different ways For example, Figure 8.19 shows the mainfeatures from the kernel in a class diagram for the familiar construct of classi-fier and how it extends from element As is shown, a classifier is a packageableelement as well as a redefined element and a namespace The definition of aclass thus extends classifier to include the additional features that make up aUML class The kernel provides a rich array of model element subclasses If anarchitectural group wants to define a cousin to UML, they derive their ownmodel elements, extending the MOF and infrastructure library where needed.However, if they only require a variant of a construct already defined in UML,they can use a profile to extend a metaclass from the metamodel
ele-Figure 8.19 Basic kernel diagram for a classifier.
RedefinableElement
NamedElement RedefinedElement Namespace PackageableElement DirectedRelationship
Classifier
isAbstract:Boolean=false isLeaf:Boolean=false
Generalization isSubstitutable:Boolean=false
Trang 15Model elements are specialized to artifacts that are useful when modelingsystems Most model elements correspond to some diagram that representsthem However, certain model elements exist without defined notation, andwith UML 2, models include additional syntax for clarity that may or may not
be displayed on a tool, depending on the vendor With UML 2, though, themodeler will always have access to this information using XML
The following high-level overview of model elements shows the type ofsemantic constructs found in UML Note that this list moves, generally, fromabstract to concrete and so should be read in order, not as some type of glos-sary (See Appendix B for a glossary of important terms.) How UML arrives atthe specific model constructs already described in this book should becomeincreasingly clear as you proceed, just as your vision becomes clearer as anoptometrist starts applying corrective lenses during an eye examination.Given the complex relationship between abstract UML elements, the order ofthe list at times reflects convenience, so the reader may experience a sensefamiliar to those who have had vision-correcting eye examinations: the inabil-ity to discern any difference after the introduction of a new lens or filter Wesuggest that you read through the whole list, remembering that the goal is tounderstand UML’s core abstractions as a foundation for developing strategiesfor applying the language to new environments Do not get caught up in ask-ing “Is it clearer now?” after each entry If you have an appetite for diggingdeeper into these abstractions, consult the UML specifications on the OMGWeb site (www.omg.org)
■■ Element.As indicated, element is the common superclass for the UMLkernel An element has no notation defined Subclasses of elementdefine notation The immediate subclasses of element have clearlydescriptive names, such as PackageableElement or GeneralizableEle-ment representing, respectively, an element you can package and oneyou can generalize
■■ Relationship.The next most important abstract class after element, arelationship is an element that provides the common superclass forindicating a connection between model elements A number of items inthe core extend relationship, such as dependency and generalization
■■ Multiplicity Element.This abstraction allows an element to have mation specifying the number of allowed elements when instantiated
infor-■■ Namespace.An abstract metaclass that allows for a named model ment to own a set of named modeled elements This abstraction allowsfor hierarchical organization of model elements
ele-■■ Expression.A string that evaluates to some value in a given context.Expression has an attribute to indicate the language used by the string
Trang 16From these high-level abstractions, we move to look at how UML handlesmore information attached to these model elements.
■■ Package.A concrete implementation of namespace that provides a
con-tainer for those elements that can be packaged
■■ Value specification.This abstraction starts the definition of values
Classes defining object instances and data values use this abstract class
meta-■■ Literal specification.Abstract specialization of value specification to
identify the values modeled The UML kernel further specializes this to
include specifications for Boolean, integer, string, unlimited naturals,
and null
■■ Instance specification.A single member or individual entity of a modelelement described by the model For example, an instance of a class is
an object A slot on an instance specification indicates if an instance
specification has values for a structural feature of the model element
Now, the list turns to classifiers and features as UML starts to come intofocus
■■ Classifier.An abstraction that classifies instances, including the
infor-mation needed to define the classification A classifier can contain a
generalization relationship, making it possible for a class, for example,
to implement a generalization hierarchy, as discussed in Chapter 4
■■ Association.A relationship between two classifiers that has a property
on both ends of the relationship to show how the classifiers participate
in the relationship
■■ Link.An instance of an association
■■ Dependency.A relationship where a model element requires other
model elements to function As shown in Chapter 4, UML includes a
number of different types of dependency relationships, such as usage,
realization, and substitution
■■ Feature.An abstract class used to characterize a classifier A behavioral
feature describes dynamic elements, while a structural feature providesthe abstraction needed for showing the descriptive elements of a
classifier
■■ Property.A structural feature of a classifier For example, when owned
by a class, it is an attribute When owned by an association, it is an ciation end
asso-■■ Parameter.The specification of a variable or argument used as input or
output with a behavioral feature Parameters can reference an operationand indicate a direction
Trang 17Finally, we turn to the more recognizable model elements.
■■ Class.A classifier that has attributes and operations as its features
■■ Operations.Owned by a class, this defines a service provided and caninclude preconditions and postconditions as UML-defined constraints
■■ Attribute.Owned by a class, this defines the structural features of theclass Use data type to show the type of values available for the struc-tural feature
■■ Data type.An abstract classifier that includes properties and operations
to show the nature of the value specification with no specific identities
So, an operation for a data type might add two integers and return aninteger, but it does not indicate the specific values returned Profiles forspecific languages typically extend data type to fit the platform
■■ Enumeration type.Extension of data type that allows for user-definedsets of values or model elements
■■ Primitive type.Base class to allow for definition of primitive types such
as Boolean, integer, or string
■■ Interface.A classifier that declares a set of public features and tions An interface must be reached by an instance of a classifier
obliga-■■ Implementation.A specialized realization relationship between a sifier and an interface
clas-■■ Association class.A model element that is both a class and an tion In other words, it has the features of both class and association
associa-■■ Powertype.A classifier that has a group of generalizations in a ization set
general-This completes the overview of the core elements of UML The additionalmodel elements in UML, such as those used in sequence diagrams and statemachines, 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 model This fact does not make them any less a part of UML; it just means theyare not covered in a section on core elements Figure 8.20 shows how UMLextends the metaclass “classifier” into many of the elements found in UML
Trang 18meta-Figure 8.20 Use of Classifier as a Superclass for UML Elements.
Trang 19Not all elements may be specialized or generalized; only generalizable ments may be specialized or generalized in the other parts of the model Thegeneralizable elements include classifier, stereotype, package, and type Ofcourse, subclasses to generalizable elements are also generalizable Subclasses
ele-of classifier include active class, signal, component, and node Thus, all theseclasses are specialized or generalized
Sometimes, it might be useful to specialize or generalize associations, butthis is not possible in UML because association is not a generalizable element
If someone has to do this, he or she needs to construct a new language from theinfrastructure library that has association as a generalizable element
The Profile Package
The infrastructure library and MOF have their own extension mechanism thatUML inherits, called the profile package An architect uses the elements in theprofile package to extend models Put another way, profile structures, whenused by a modeler, contain variants of the UML metamodel elements tuned to
a specific need A profile relates directly to a reference metamodel; it cannotcreate new constructs not defined in a single metamodel For new constructs,
an architect has to create a new metamodel using MOF The definition of OCLreviewed earlier represents the approach of defining entirely new concepts Interms of UML, however, the profile mechanism supports most of the extensionneeds of UML users
In addition, users of UML might not need to define their own profiles Othershave already spent a lot of time and effort testing the profiles so that they workeffectively, and tool vendors package the more common of these with theirUML tools UML profiles represent an effective way to manage the inevitableadaptations users must make to adapt the UML metamodel, while at the sametime providing consistent automated support Given the proliferation of plat-forms and the pace of technological change, no modeling language can providethe semantic detail to apply across platforms Profiles as a fully defined high-level package much improve the extension mechanisms in UML, making it eas-ier for modelers to communicate with synchronized models
Profiles have become more prominent, in part due to the popularity ofextension mechanisms and UML With the proliferation of user-defined vari-
ants, custom-built UML in 1.x did not always work smoothly Modelers
pro-duced a number of constructs covering such areas as Web applications,real-time systems, data modeling, Enterprise JavaBeans, and framework archi-tectures Some tool vendors developed their own variants and packaged theminto versions of their UML model tools Understandably, because these pro-files had no standards, interoperability emerged as a concern So, for example,
Trang 20one user might have a particular definition of an <<EJB>> stereotype, whileanother modeler might use the same stereotype tag defined in a slightly dif-ferent manner, perhaps for a different version of Enterprise JavaBeans UML
1.x profiles had particular problems as platform-specific information changed
as language versions altered the meaning of the platform-specific conceptsover time
Currently, OMG seeks to manage approved profiles to help improve operability Already, OMG has an approved profile for Common ObjectRequest Broker Architecture (CORBA), and their Web site has draft specifica-tions for such things as Enterprise Application Integration (EAI), as well asschedulability, performance, and time specification A profile for EnterpriseJavaBeans, the wider Java language, and NET are in the works
inter-The requirements for UML 2 made it clear that the new version needed tosupport a general mechanism to allow users to adapt the language, whileallowing them to manage conflicting extensions The profile mechanism cou-pled with the requirement to express models using XML realizes this require-ment for casual UML users
It is possible to extend any element in the UML metamodel with a profile Tomodel such an extension, use features from the profiles package In creating astereotype, a user can also define a set of properties or constraints on that ele-ment The example shows a definition of a stereotype and then an application
of that stereotype Figure 8.21 shows a stereotype extending a metaclass Inthis case, the model defines a stereotype “primate.” This stereotype takes oneproperty, chromosomes, with a type of integer, which shows how many chro-mosomes the primate has Figure 8.22 shows the stereotype in action, with theApe and Human classes both with the primate stereotype A fully compliantUML tool knows to look for the defined property of chromosome In a profile,
an extension has special notation, shown as an arrow with a solid black gle on the end pointing toward the metaclass that the stereotype extends Atagged value is a user-defined property of a stereotype, applied to the modelelement when the base metaclass is extended
trian-Figure 8.21 Sample stereotype extension.
Trang 21Figure 8.22 Classes built from a defined stereotype.
In UML, a modeler applies a profile to his or her model using a dependencyrelationship with a stereotype of <<apply>> Figure 8.23 shows an example ofhow to apply a profile, showing the reference metamodel and the profile Therelationship between the profile and the reference metamodel can be modeledwith more specific information Such a relationship defined at a high level willhelp the UML tool manage which profile you are using on a specific model,avoiding the problem of conflicting names However, do not attempt to rede-fine the name of the existing standard stereotypes in UML, because all thesestereotypes are applied automatically
C R O S S - R E F E R E N C E For an updated list of available profiles, visit the
OMG Web site (www.omg.org).
Figure 8.23 Applying a profile that uses UML as the reference metamodel.
Trang 22Architecture Overview Summary and Observations
The element is the abstract base class for most constituents of the UML; it vides an anchor to which a number of mechanisms may be attached The meta-model specializes element into model elements, relationships, namespaces,value specifications, classifiers, classes, and so on, with the UML specificationproducing a large number of subclasses that define the constructs explained inthe book as part of the UML toolkit, such as use cases, components, classes,state machines, activity diagrams, sequence diagrams, and deployments Thebreakdown in this section illustrates the many different levels on which toapproach UML Those using a modeling tool for a basic class diagram need notknow how UML was built, just that it allows the display of a class rectanglethat also links to the code for that class in an implementation language
pro-This definition of UML in terms of general modeling concepts makes it morelikely that vendors will enable model sharing and support user-defined adap-tations of UML So, for most users of UML, this means it will be easier to sharemodels with others and have the tools understand what they mean Of course,
if the modeler can’t communicate using these tools, then this is an opportunitywasted The goal for these extensions is to enable communication and targetedcustomization, not abstraction for its own sake
This discussion of the metamodel shows how the designers of UML allowedfor user input If a tagged value, stereotype, or constraint is attached to amodel element, a specialization to that model element has the same taggedvalue, stereotype, or constraint For most purposes, modelers should use thesefeatures to improve their models However, avoid using these features to clut-ter a model with excessive detail that is not needed These extensions havepractical purposes, and modelers should always look for the reasons forapplying an extension or profile before they take the trouble of integrating thenew material into their model As with everything in UML, just because thelanguage offers you a feature does not mean that using that feature will bringproject success For more on model quality, see Chapter 10
Relevant Changes in UML 2
UML 2 presents the modeler with a rather different extension architecturedesigned to provide more options, smoother tool support, and clearer defini-tions for machines No longer does UML use UML to define its own model.The core UML metamodel now reflects another set of modeling concepts in theMOF, giving the modeling community the ability to supplement UML by cre-ating a cousin of UML This new ability to create another member of the UMLfamily of languages has resulted in the separate specification of a constraint
Trang 23language with OCL, no longer defined in the UML specification The profilesmechanism, a less drastic way of extending UML, also has a clearer definition,showing the way a stereotype maps to an element in the metamodel.
With the requirement to express these extensions using XMI, UML now has
a standard that makes it easier for tool vendors to support common
exten-sions Under UML 1.x, tool vendors added in their own special extensions to
UML, but a modeler using a different tool would not be able to understandthose elements With UML 2, a modeler can explicitly indicate which profilehis or her model applies, so any other user can get the same profile for the sys-tem to work This language architecture is designed to support a proliferation
of model extensions as architects seek to extend UML concepts to newdomains This flexibility has helped UML expand; now, the extensions can bemore clearly managed
A number of standard elements from version 1.x have been retired or
pro-moted The long-range vision for these extensions involves coherent and trolled packaging of extensions into profiles UML still uses its ownstereotypes and profiles and will continue to do so, but these should supportUML’s core aim as a language to model systems that use information technol-ogy 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 modelinglanguage
con-Why does UML 2 need such extension features? con-Why did the designers ofUML 2 put so much effort into redefining the language architecture to allowsuch extensions? The next chapter on MDA helps to explain the larger knowl-edge management goals of the UML community and how the new internalarchitecture supports these ambitions
Summary
All model languages have restrictions and limits When a language is too eral, it undermines the possibility of making distinct and sharp statements;when it is too specialized, it limits the possible statements C++ can be seen as
gen-a modeling lgen-angugen-age specigen-alized for progrgen-amming but not thgen-at powerful forbusiness modeling Therefore, UML is defined with a limited number of gen-eral elements and armed with extension mechanisms
UML uses profiles as an internal way to organize the three main extensionmechanisms: tagged values, constraints, and stereotypes These mechanismsare used to define a set of standard extensions included in UML, to which newextensions may be added (user-defined extensions) Extensions are typicallyadded to adapt UML to a method, an organization, or a specific applicationdomain
Trang 24Profiles extend the UML metamodel as their starting point UML also offers
a more elaborate extension mechanism to specify a completely new modelinglanguage, separate from UML but related by a common parent For both ofthese extension strategies to work, the modeler needs to have a firm grasp ofthe details in the UML high-level model
Tagged values are a mechanism for adding extra information to the modelsand their elements The information may be intended both for human beingsand for machines (such as code generators or UML tools)
Constraints are used to restrict the semantics of the elements within theUML A constraint might not add extra meaning, only limit the existingsemantics of the elements OCL provides the supported way to express con-straints so that tools can interpret these rules
Stereotypes are used for specializing semantics of the UML metamodel.They enable you to define and model with higher precision Bundled into pro-files, stereotypes are the core extension mechanism within UML Modelersshould use these extension mechanisms to improve model quality and avoidthe temptation to model to a degree of precision not needed for project success.The changes in the language architecture for UML 2 do have a practical pur-pose UML 2 requires such support for extensions in response to the problem
of the proliferation of middleware platforms Modelers can use these features
as they try to extend UML to help it address complex information ment systems, deployed systems that need to change platforms, and dispersedsystems such as Web applications The MDA initiative provides the guidingarchitectural statement that organizes these features into a coherent approach
manage-to software development The next chapter provides an overview of MDA
Trang 26The Model Driven Architecture (MDA) initiative seeks to make UML modelsmore useful for the distributed and integrated software systems so preva-lent today MDA places the model at the center of information management,applying UML models to manage complex systems Such a prominent effortfrom the keepers of UML raises some questions for users of UML tools, like the following
■■ What does MDA have to do with UML?
■■ What drives the MDA initiative?
■■ What role does UML play in the structure of MDA?
■■ How does MDA influence the revisions to UML?
■■ Looking to the future, what type of evolution might you anticipate fromUML/MDA?
These questions define this chapter For a more complete review of MDAand the latest case studies, see the OMG Web site Here, the focus is on MDA
as an architectural strategy that has influenced and continues to influenceUML After a review of MDA goals and definitions, the chapter looks at thevarying types of modeling activities that MDA emphasizes at different levels
of abstraction MDA will likely require modelers to change their emphasis, so
Model Driven Architecture
9
Trang 27this chapter summarizes some of the modeling demands of the MDA ment The chapter concludes with a brief assessment of the relationshipbetween MDA and UML and the opportunities for the future.
environ-MDA Evolution and Goals
What is MDA? MDA is an architectural statement by the OMG that providesguiding principles to coordinate a variety of activities under the umbrella ofmaking modeling artifacts capable of doing more work to solve integrationproblems Although MDA is recent, the general trends it represents are not
Background and General Goals
With a white paper in November 2000, the OMG first proposed MDA as a way
to use advanced modeling technology to address the confusion caused by theproliferation of middleware platforms In February 2001, the OMG formallyput their efforts behind the initiative and began work on elaborating the visionfrom this initial white paper Unlike UML, which produced specification doc-uments numbered in the hundreds of pages, MDA uses short documents thatfocus on important themes MDA themes have appeared in a number of booksand articles to promote this approach to using models OMG committees haveworked on short “technical perspective” documents as well as some generalframework models to provide greater definition In May 2003 the OMG pub-lished version 1.0 of the MDA Guide to reflect these efforts Large companies,already in pursuit of MDA goals, have joined in the effort through the OMGand have helped shape UML to support MDA
MDA resembles a previous initiative In 1990, the OMG had an Object agement Architecture (OMA) as an architectural statement to provide guid-ance on how to address integration issues This related to the work definingthe Common Object Request Broker Architecture (CORBA) that helped solve anumber of integration issues MDA provides a similar architectural statementbut one that addresses integration issues on the complex enterprise systemsnow deployed With the expansion of UML specifications and the growingnumber of profiles, the relationship between the different groups of OMGstandards becomes complex For example, how does the latest profile on enter-prise application integration relate to OMG’s goals? How will the modelingcommunity assess these efforts? How does the Meta-Object Facility (MOF), thelanguage used to define UML, help those producing software? MDA provides
Man-a common bMan-ackground Man-and vision thMan-at explMan-ains the purpose of these vMan-ariedinitiatives