Tải bản đầy đủ - 0 (trang)
Chapter 17. Creating New Extension Points

Chapter 17. Creating New Extension Points

Tải bản đầy đủ - 0trang

17.1.TheExtensionPointMechanism

Uptothispoint,wehavebeendiscussingextensionpointsasa

consumer;nowweneedtodelveintothemechanismbehind

thecurtainsothatultimatelyyoucanproduceyourown

extensionpointsforotherstoconsume.Notonlywillextension

pointsmakeproductsmoreflexible,butalso,bycarefully

exposingspecificaspectsofyourplug-in,youcanmakeyour

productsmoreflexibleandcustomizable.Thegoalisto

empoweryourcustomerstotakeproductsanddothingsthat

wereneverenvisioned.

ExtensionpointsareusedthroughoutEclipseasamechanism

forlooselycouplingchunksoffunctionality.Oneplug-indeclares

anextensionpointinitsplug-inmanifest,exposingaminimal

setofinterfacesandrelatedclassesforotherstouse;other

plug-insdeclareextensionstothatextensionpoint,

implementingtheappropriateinterfacesandreferencingor

buildingontheclassesprovided(seeFigure17-1).



Figure17-1.Extensionpointoverview.



[Viewfullsizeimage]



Eachextensionpointhasauniqueidentifiercomposedofthe

plug-in'suniqueidentifier,aperiod,andasimpleidentifier

containingonlyalpha-numericcharactersandunderscores.

Whendeclaringanextensionpoint(seeSection17.2.1,

Creatinganextensionpoint,below),onlythesimpleidentifieris

used.Whendeclaringanextensiontoanextensionpoint(see



Section17.5,UsingtheExtensionPoint,onpage615),thefull

identifierfortheextensionpointisused.

Everyextensionpointcanhaveaschemadefininghowthey

shouldbeused.Althoughtheschemaisnotnecessaryfor

properextensionpointusage,theEclipsePDEcanusethe

schemaforbasicautomatedverificationofextensionsand

automaticallygeneratedJavadoc-likedocumentationforthe

extensionpoint.

TheschemaisanXML-formattedfile,traditionallyhavingthe

name.exsdandislocatedinaschema

subdirectoryoftheplug-in'sinstalldirectory.Forexample,the

extensionpointschemadiscussedlaterinthischapterwillbe

storedin/plugins/

com.qualityeclipse.favorites_1.0.0/schema/favorites.exsd.



17.2.DefininganExtensionPoint

IntheFavoritesproduct,youwouldlikeotherplug-instoextendyourproductto

provideadditionaltypesofFavoritesobjects.Toaccomplishthisgoal,createanew

favoritesextensionpointandschemaplusrelatedinfrastructuretypesthatotherscan

extend.Aspartofthisprocess,recastthecurrentFavoritesobjectsasextensionsto

thisnewextensionpointtoprovetoyourselfthatthenewextensionpointdoes

indeedwork.



17.2.1.Creatinganextensionpoint

BeginbyopeningtheFavoritesplug-inmanifesteditorandswitchingtothe

ExtensionPointspage.ClicktheAdd...buttontoopentheNewExtensionPoint

wizard,andthenenter"favorites"fortheidentifierand"Favorites"forthename(see

Figure17-2).



Figure17-2.TheNewExtensionPointwizard.



ClickFinishtocreatethenewextensionpointandopentheschemafile(moreon

schemasinSection17.2.2,Creatinganextensionpointschema,onpage599).After

switchingbacktotheplug-inmanifesteditor,theExtensionPointspageshould

showthenewlydefinedextensionpoint(seeFigure17-3).



Figure17-3.TheExtensionPointspageintheplug-inmanifest

editor.



[Viewfullsizeimage]



Switchingtotheplugin.xmlpageoftheplug-inmanifesteditorrevealsanew

extensionpointdeclarationspecifyingtheidentifier,thehuman-readablename,and

therelativelocationoftheschema.


id="favorites"

name="Favorites"

schema="schema/favorites.exsd"/>



Theaforementioneddeclarationspecifiesthelocalidentifieroftheextensionpoint.

Thefullidentifieristheplug-inidentifierplusthelocalidentifierandisusedwhen

referencingtheextensionpoint;inthiscase,thefullidentifieris

com.qualityeclipse.favorites.favorites.



17.2.2.Creatinganextensionpointschema

TheNewExtensionPointwizardautomaticallyopenstheschemaeditortoeditthe

newlycreatedfavorites.exsdfileintheschemadirectoryoftheFavoritesproject(see

Figure17-4).Ifyoueverneedtoopentheschemaeditoragain,youcaneither

navigatetotheschemadirectoryanddouble-clickonthefavorites.exsdfile,orselect

thefavoritesextensionpointintheFavoritesplug-inmanifest,right-click,andthen

selectOpenSchema.



Figure17-4.TheEclipse3.1Extensionpointschemaeditorshown

ontheleft,andtheEclipse3.2Extensionpointschemaeditor

shownontheright.



[Viewfullsizeimage]



Theschemaeditorhasseveralmajorparts:GeneralInformation,ExtensionPoint

Elements,ElementGrammar,andDocumentation.NotethatbetweenEclipse3.1

and3.2,thepagesandsectionsofthiseditorhavebeenrearranged;however,the

basicprinciplesinusingitremainthesame.

TheExtensionPointElementslistcontainselementsandtheirassociated

attributes,whichappearasextensionstotheextensionpoints(seeSection17.2.3,

Extensionpointelementsandattributes,onthenextpage).

InEclipse3.1,theElementGrammarlistcontainsadescriptionofhowtheXML

elementsshouldappearintheextension(seeSection17.2.4,Extensionpoint

elementgrammar,onpage605).InEclipse3.2,thissectionhasbeencombinedwith

theExtensionPointElementslist.

Tostart,documentthegoalsothatyouhaveaclearviewofwhatyouaretryingto

accomplish.AnextensionpointschemaisusedbythePDEtodynamicallyassemblea

helppagefortheextensionpoint(seeSection17.4,ExtensionPointDocumentation,

onpage614).IntheDescriptionsectionoftheschemaeditor(ontheDefinition

pageoftheeditorinEclipse3.1andontheOverviewpageinEclipse3.2),enterthe

followingdescription,andthenclicktheApplybutton.

TheFavoritesviewcontainsandpersistsacollectionofobjects

existingintheEclipseworkspace.ThisFavoritesextensionpoint

allowsthird-partyplug-instodefinenewtypesofobjectsforthe

Favoritesview.



RepeatthisprocessbyselectingtheExamplestabintheDocumentationsection

andenteringthefollowingtext(seebelow).Notetheuseofthe
and
XML

tagstodenotepreformattedtextinwhichwhitespaceshouldbepreserved;allother



whitespacegreaterthanasinglespaceoutsidethosetagsisdiscardedinthe

automaticallygeneratedHTMLhelptext(seeSection17.4,ExtensionPoint

Documentation,onpage614).

Thefollowingisanexample

oftheFavoritesextensionpointusage:








id="com.example.xyz.myNewFavoriteItemId"

name="NewFavoritesItemName"

class="com.example.xyz.MyFavoriteItem"

targetClass="com.example.xyz.MyObjectClass"/>









Then,forAPIInformation,enterthefollowing:

Plug-insthatwanttoextendthisextensionpointmustsubclass

com.qualityeclipse.favorites.model.FavoriteItemTypeand

generateobjectsthatimplementthecom.qualityeclipse.favorites.model.IFavoriteIteminterface.



NotetheusetheXMLtagstodenotecodeinasentence

similartothewaythatmanyoftheEclipseplug-insaredocumented;the

XMLtagsshouldworkjustaswell.



17.2.3.Extensionpointelementsandattributes

ExtensionpointelementscorrespondtoXMLelementsthatappearintheextension

declaration.ExtensionpointattributescorrespondtoXMLattributesthatappearin

theextensiondeclaration.Forexample,inthefollowingextensiondeclaration,

itemTypeisanextensionpointelement,whileid,name,class,andtargetClassare

extensionpointattributes.


"com.qualityeclipse.favorites.favorites">


id="com.example.xyz.myNewFavoriteItemId"

name="NewFavoritesItemName"

class="com.example.xyz.MyFavoriteItem"

targetClass="com.example.xyz.MyObjectClass"/>





Extensionpointattributeshaveseveraldifferentpropertiesassociatedwiththem.In

Eclipse3.1,double-clickingonanattributeintheschemaeditoropensthe

Propertiesviewanddisplaystheproperties(seeFigure17-5).InEclipse3.2,the

Propertiesviewisnolongerusedtoeditthepropertiesastheyarenowshown

directlyintheAttributeDetailssectionoftheschemeeditor.Thepropertiesfor

extensionattributesare:

NameThenameoftheattributeasitappearsintheextension'sdeclaration.

Forexample,intheaforementionedextensiondeclaration,id,name,class,and

targetClassareallattributenames.

TypeThetypeoftheattribute:stringorBoolean.Atthistime,thesearethe

onlytwotypesrecognizedbytheschemaeditorandPDE.Ifyourattribute

shouldonlybetrueorfalse,thenselectboolean;forallotherattributes,select

string.

UseIndicateswhetherthisattributeisrequiredinanextensionandthusmust

beexplicitlydeclared,orwhetheritisoptional,indicatingthatitmaybeomitted

fromanextensiondeclaration.Alternately,theUsemaybedeclaredasdefault,

indicatingthatifitisnotexplicitlydeclared,thenitdefaultstothevalue

specifiedbytheValuepropertylistedlater.

KindIftheaforementionedTypepropertyisstring,thenthispropertyindicates

howthatstringshouldbeinterpreted:asajavaclass,asaresourcepathtoan

image,orsimplyasastringfortheextensionpointcodetointerpretasitlikes.

BasedOnIftheKindisjava,thenthispropertyindicatesthefullyqualified

nameoftheclassorinterfacethatthisattributemustextendorimplement.In

Eclipse3.2,thispropertyhasbeensplitintoseparateExtendsand

Implementsproperties(seeFigure17-5).

RestrictionIftheTypeisstringandtheKindisstring,thenthispropertycan

restrictthevalueoftheattributetoanenumerationordiscretelistofvalid

strings.Forexample,usingthisfield,youcouldspecifythatanattributecould

onlyhavethevalue"one","two",or"three".

TranslatableAbooleanindicatingwhetherthisattributeishumanreadable

andshouldbetranslated.

ValueIftheUseisspecifiedasdefault,thenthispropertyindicatesthedefault

valuethatwillbeusedifthisattributeisnotexplicitlyspecifiedinthe

extension'sdeclaration.



Figure17-5.TheEclipse3.1Propertiesviewshowingattribute

propertyvaluesontheleftandtheEclipse3.2AttributeDetails

areashowingthosesamepropertiesontheright.



[Viewfullsizeimage]



FortheFavoritesproduct,youwantextensionstothisextensionpointtospecify

informationaboutthetypeofFavoritesitembeingadded.Thefollowingarethe

extensionpointattributestoinclude.

nameThehuman-readablename.

idTheuniqueidentifier.

iconTherelativepathtoanimage(optional).

classTheFavoriteItemFactoryforcreatingitemsofthistype.

targetClassThetypeofobjectbeingwrappedbythistype.



Tip

Ifyourextensionpointisintendedforgeneralconsumption,thenhavea

planforlazyextensioninitializationsothatyoudonotcausemorepluginsthanneedtobeloaded,resultinginmemorybloatandslowingdown

thesystem.Forexample,inthiscase,thetargetClassisusedtodetermine

whichFavoritesitemtypeshouldbeusedbeforetheplug-inthatdefines

itisactuallyloaded.Ifyoudonothavethisinformationspecifiedinthe

extension,thenwhenusersdraganddropnewobjectsontothe

Favoritesview,theywouldneedtoloadandqueryeachFavoritestype

todeterminewhichtypeshouldhandlethedroppedobjects.Thiscould

potentiallypullinmanymoreplug-insthannecessary,bloatingand

slowingdowntheworkspace.

Instead,youpre-screenthetypesbasedonthetargetClasstodetermine

whichtypemaybeabletohandlethedroppedobject.Ifyourextension

pointisintendedforuseonlywithinyourownplug-in,thenyoudonot

needtheextracomplexityandoverheadassociatedwithaproxy.



First,youneedtoaddanitemTypeelementrepresentingtheFavoritesitemtype

beingdefined,towhichyouwilladdtheseattributes.Toaccomplishthis,switchtothe



Definitionpage,clickontheNewElementbutton,selectthenew_element1thatwas

created,andchangethenameto"itemType".

TochangethenameinEclipse3.1,youwillneedtodouble-clickontheelementto

openthePropertiesview.InEclipse3.2,thenameisshowndirectlyinthe

AttributeDetailssectionoftheschemeeditor.

WithitemTypeselectedintheschemaeditor,clicktheNewAttributebuttontoadda

newattributetotheitemTypeelement.Changeitsnameto"name".Withthename

attributeselectedintheschemaeditor,enter"Ahuman-readablenameforthistype

ofFavoritesobject."forthedescriptionofthenameattributeandthenclickApply.

Repeatthisprocesstoaddfourmoreattributes.Whenyouaredone,youshouldhave

definedthefollowingattributesfortheitemTypeelementwiththepropertiesspecified

here.

attribute#1

name="name"

use="optional"

kind="string"

translatable="true"

description="Ahuman-readablenameforthistypeofFavoritesobject."

attribute#2

name="id"

use="required"

kind="string"

description="TheuniqueidentifierforthistypeofFavoritesobject."

attribute#3

name="icon"

use="optional"

kind="resource"

description="AnoptionimageassociatedwiththistypeofFavorites

object."



attribute#4

name="class"

use="required"

kind="java"

basedOn/extends

="com.qualityeclipse.favorites.model.FavoriteItemFactory"

description="Thefullyqualifiednameoftheclassthatextends

com.qualityeclipse.favorites.model.FavoriteItemFactory."

attribute#5

name="targetClass"

use="required"

kind="string"

description="Thefullyqualifiednameoftheclasswrappedbythisitem

type.ThisisnottheclassnamefortheIFavoriteItemobjectreturnedby

eitherFavoriteItemType.loadFavorite(String)or

FavoriteItemType.newFavorite(Object),butratherthe

objectwrappedbythatIFavoriteItemobjectthatcausesthe

IFavoriteItem.isFavoriteFor(Object)toreturntrue."



Tip

Howshouldanextensionprovidebehaviorforyourextensionpoint?Do

youneedextensionstoimplementaninterfaceorinsteadextendan

abstractbaseclass?Ifyouneedextensionstoimplementaninterface,

thenyougrantmoreflexibilitytotheextensionwriter.Onthedownside,

anychangetothatinterfacewillbreakexistingextensions.Instead,ifyou

needextensionstoextendanabstractbaseclass,thenyoukeepsome

flexibilitywhilestillretainingadvantagesofloosecoupling.Addinga

concretemethodtoanabstractbaseclasswillnotbreakexisting

extensions,givingyoutheopportunitytochangetheAPIinfuture

implementations,allwithoutsacrificingmuchoftheextensionwriter's

flexibility.IfyouaresurethatyourAPIwillnotchange,thenaninterface

isagreatwaytogo;otherwise,anabstractbaseclassgivesyouthe

flexibilityyouneedtoevolvetheAPI.

Ifyouneedtheflexibilityofaninterfacewhereanabstractbaseclasswill

notdo,thenconsiderrequiringtheinterfacebutprovidinganabstract

baseclassthatimplementsthatinterfaceforextensionstobuildonifthey

choose.Giventhisapproach,youcanchangetheinterfaceAPIand

mitigatedisruptionbyaddingconcretemethodsinyourabstractbase



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 17. Creating New Extension Points

Tải bản đầy đủ ngay(0 tr)

×