Tải bản đầy đủ - 0 (trang)
Chapter 14. Bless Those Things! (Object-Oriented Perl)

Chapter 14. Bless Those Things! (Object-Oriented Perl)

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

thedataisthroughthesepublicmethods.Ifyouhaveanobject

called"money",themethodsmightbeearnit(),findit(),

stealit(),etc.

Thedataandthemethodsarepackagedupintoadata

structurecalledaclass.APerlpackagewillfunctionasaclass

whenusingtheobject-orientedapproach.Thisisnotreallya

newideaforPerl,sincedataisalreadyencapsulatedin

packages.Recallfromourshortdiscussionofpackagesthata

packagegivesasenseofprivacytoyourprogram.Each

packagehasitsownsymboltable,ahashthatcontainsallthe

namesinthe"current"package.Thismakesitpossibleto

createvariablesandsubroutinesthathavetheirown

namespacewithinapackage.Whenusingdifferentpackages

withinyourprogram,eachpackagehasitsownnamespace,

thusprotectingtheaccidentalclobberingofvariableswiththe

samename.Theideaofhidingdatainpackages,then,is

inherentlypartofPerlandalsohappenstobeoneofthebasic

tenetsofobject-orientedprogramming.

EveryPerlprogramhasatleastonepackagecalledmain,where

Perlstatementsareinternallycompiled.ThestandardPerl

libraryconsistsofanumberoffilescontainingpackages.Most

ofthesefilesarecalledmodules.Amoduleisreallyjusta

fancypackagethatisreusable.Thereuseofcodeisdone

throughinheritance;thatis,apackagecaninherit

characteristicsfromaparent,orbase,classandthusextendor

restrictitsowncapabilities.Theabilitytoextendthe

functionalityofaclassiscalledpolymorphism.Hidingdata

(encapsulation),inheritance,andpolymorphismareconsidered

thebasictenetsoftheobject-orientedphilosophy.

TocreateaPerlmodule,youstillusethepackagekeyword,and

thescopeisfromthedeclarationofthepackagetotheendof

theenclosingblockorfile.Packagesnormallyarethesizeof

onefile.Thefilescanberecognizedasmodulesiftheirnames

endwitha.pmextensionandifthefirstletterofthemoduleis

capitalized.Pragmasareanotherspecialkindofmodule(the



nameisspelledinlowercasebutstillhasthe.pmextension)

thatdirectsthecompilertobehaveinaspecifiedway.Whether

thepackageiscalledamoduleorapragma,ithassomespecial

featuresthatdifferentiateitfromanordinarypackage.Those

specialfeaturesintroducedinPerl5giveyoutheabilityto

modelyourprogramswiththeobject-orientedwayofabstract

thinking.YoucanthinkofprocedurallanguagesasactionorientedandOOlanguagesasobject-oriented.

TomChristianson,discussingPerlandobjectsonhisWebpage

"EasyPerl5ObjectIntro,"saysthatpeopletendtoshyaway

fromhighlyconvenientPerl5modulesbecausesomeofthem

dealwithobjects.Unfortunately,someproblemsverymuch

lendthemselvestoobjects.Christiansonsaysthatpeople

shouldn'tbescaredbythis,becausemerelyknowingenough

OOprogrammingtousesomeoneelse'smodulesisnotnearly

asdifficultasactuallydesigningandimplementingoneyourself.

[1]Evenifyouarenotinterestedinwritingprogramsthattake

advantageoftheOOPfeaturesofPerlbutstillneedtousePerl

modulesthatdoutilizeobjects,readingthroughthischapter

shouldgreatlyenhanceyourunderstandingofhowthese

moduleswork.

[1]Gotowww.perl.com/CPAN-local/doc/FMTEYEWTK/easy_objects.htmltosee



TomChristianson'sWebpage.



14.1.2.SomeObject-OrientedLingo

Object-orientedprogrammingisahugesubject.Thousandsof

bookshavebeenwrittenonOOprogramming,design,and

methodology.Manyprogrammersofthe1990smovedaway

fromtraditionaltop-downstructuredprogrammingandtoward

object-orientedprogramminglanguagesforbuildingcomplex

software.Thisisnotabookonobject-orienteddesignor

programming.However,therearesomebasickeywords

associatedwithOOPthatshouldbementionedbeforetackling

Perl'sOOPfeatures.TheyarelistedinTable14.1.

Table14.1.KeyOOPWords



Word



PerlMeaning



Data

encapsulation



Hidingdataandsubroutinesfromthe

user,asinapackage



Inheritance



Thereuseofcode,usuallyfroma

librarywhereapackageinheritsfrom

otherpackages



Polymorphism



Literally"manyforms"andspecifically,

theabilitytoextendthefunctionality

ofaclass



Object



Areferencedtypethatknowswhat

classitbelongsto;aninstanceofa

class



Method



Aspecialsubroutinethatmanipulates

objects



Class



Apackagethatcontainsdataand

methods



Constructor



Amethodthatcreatesandinitializes

anobject



Destructor



Amethodthatdestroysanobject



Setters/Getters Methodsthatstoredatainanobject

orfetchdatafromanobject



Chapter14.BlessThoseThings!(ObjectOrientedPerl)

TheOOPParadigm

Classes,Objects,andMethods

AnonymousSubroutines,Closures,andPrivacy

Inheritance

PublicUserInterface—DocumentingClasses

UsingObjectsfromthePerlLibrary

WhatYouShouldKnow

What'sNext?



14.1.TheOOPParadigm

14.1.1.PackagesandModulesRevisited

ThebigadditiontoPerl5wastheabilitytodoobject-oriented

programming,calledOOPforshort.OOPiscenteredontheway

aprogramisorganized.Object-orientedlanguages,suchas

C++andJava,bundleupdataintoavariableandcallitan

object.AnobjectcanbedescribedasanouninEnglish:a

person,place,orthing.Acat,acomputer,andanemployeeare

objects.Adjectivesdescribenouns.Forexample,thecatis

sneaky,thecomputerisfast,theemployeeiscalled"John."In

OOlanguages,theadjectivesthatdescribetheobjectarecalled

properties,alsocalledattributes.Verbsthatdescribewhat

theobjectcandoorwhatcanbedonetoitarecalledmethods

inOO.Thecateats,thecomputercrashes,theemployee

works.Perlmethodsarejustspecializedsubroutines.

Theobject'sdataisnormallykeptprivate.Messagesaresent

totheobjectthroughitsmethods.Themethodsarenormally

public.Theonlywaythatauseroftheprogramshouldaccess



thedataisthroughthesepublicmethods.Ifyouhaveanobject

called"money",themethodsmightbeearnit(),findit(),

stealit(),etc.

Thedataandthemethodsarepackagedupintoadata

structurecalledaclass.APerlpackagewillfunctionasaclass

whenusingtheobject-orientedapproach.Thisisnotreallya

newideaforPerl,sincedataisalreadyencapsulatedin

packages.Recallfromourshortdiscussionofpackagesthata

packagegivesasenseofprivacytoyourprogram.Each

packagehasitsownsymboltable,ahashthatcontainsallthe

namesinthe"current"package.Thismakesitpossibleto

createvariablesandsubroutinesthathavetheirown

namespacewithinapackage.Whenusingdifferentpackages

withinyourprogram,eachpackagehasitsownnamespace,

thusprotectingtheaccidentalclobberingofvariableswiththe

samename.Theideaofhidingdatainpackages,then,is

inherentlypartofPerlandalsohappenstobeoneofthebasic

tenetsofobject-orientedprogramming.

EveryPerlprogramhasatleastonepackagecalledmain,where

Perlstatementsareinternallycompiled.ThestandardPerl

libraryconsistsofanumberoffilescontainingpackages.Most

ofthesefilesarecalledmodules.Amoduleisreallyjusta

fancypackagethatisreusable.Thereuseofcodeisdone

throughinheritance;thatis,apackagecaninherit

characteristicsfromaparent,orbase,classandthusextendor

restrictitsowncapabilities.Theabilitytoextendthe

functionalityofaclassiscalledpolymorphism.Hidingdata

(encapsulation),inheritance,andpolymorphismareconsidered

thebasictenetsoftheobject-orientedphilosophy.

TocreateaPerlmodule,youstillusethepackagekeyword,and

thescopeisfromthedeclarationofthepackagetotheendof

theenclosingblockorfile.Packagesnormallyarethesizeof

onefile.Thefilescanberecognizedasmodulesiftheirnames

endwitha.pmextensionandifthefirstletterofthemoduleis

capitalized.Pragmasareanotherspecialkindofmodule(the



nameisspelledinlowercasebutstillhasthe.pmextension)

thatdirectsthecompilertobehaveinaspecifiedway.Whether

thepackageiscalledamoduleorapragma,ithassomespecial

featuresthatdifferentiateitfromanordinarypackage.Those

specialfeaturesintroducedinPerl5giveyoutheabilityto

modelyourprogramswiththeobject-orientedwayofabstract

thinking.YoucanthinkofprocedurallanguagesasactionorientedandOOlanguagesasobject-oriented.

TomChristianson,discussingPerlandobjectsonhisWebpage

"EasyPerl5ObjectIntro,"saysthatpeopletendtoshyaway

fromhighlyconvenientPerl5modulesbecausesomeofthem

dealwithobjects.Unfortunately,someproblemsverymuch

lendthemselvestoobjects.Christiansonsaysthatpeople

shouldn'tbescaredbythis,becausemerelyknowingenough

OOprogrammingtousesomeoneelse'smodulesisnotnearly

asdifficultasactuallydesigningandimplementingoneyourself.

[1]Evenifyouarenotinterestedinwritingprogramsthattake

advantageoftheOOPfeaturesofPerlbutstillneedtousePerl

modulesthatdoutilizeobjects,readingthroughthischapter

shouldgreatlyenhanceyourunderstandingofhowthese

moduleswork.

[1]Gotowww.perl.com/CPAN-local/doc/FMTEYEWTK/easy_objects.htmltosee



TomChristianson'sWebpage.



14.1.2.SomeObject-OrientedLingo

Object-orientedprogrammingisahugesubject.Thousandsof

bookshavebeenwrittenonOOprogramming,design,and

methodology.Manyprogrammersofthe1990smovedaway

fromtraditionaltop-downstructuredprogrammingandtoward

object-orientedprogramminglanguagesforbuildingcomplex

software.Thisisnotabookonobject-orienteddesignor

programming.However,therearesomebasickeywords

associatedwithOOPthatshouldbementionedbeforetackling

Perl'sOOPfeatures.TheyarelistedinTable14.1.

Table14.1.KeyOOPWords



Word



PerlMeaning



Data

encapsulation



Hidingdataandsubroutinesfromthe

user,asinapackage



Inheritance



Thereuseofcode,usuallyfroma

librarywhereapackageinheritsfrom

otherpackages



Polymorphism



Literally"manyforms"andspecifically,

theabilitytoextendthefunctionality

ofaclass



Object



Areferencedtypethatknowswhat

classitbelongsto;aninstanceofa

class



Method



Aspecialsubroutinethatmanipulates

objects



Class



Apackagethatcontainsdataand

methods



Constructor



Amethodthatcreatesandinitializes

anobject



Destructor



Amethodthatdestroysanobject



Setters/Getters Methodsthatstoredatainanobject

orfetchdatafromanobject



14.2.Classes,Objects,andMethods

14.2.1.RealWorld

Supposeyouwanttobuildahouse.First,youwouldbuya

pieceofpropertylocatedataspecificaddress.Thenyouwould

hireanarchitectorbuyaprogramforyourcomputertohelp

designthehouse.Youwoulddecidewhattype,style,howmany

rooms,doors,windows,etc.Afteryoudesignthehouse,you

willhireacontractortobuildthehouse.Onceit'sbuilt,you

haveaccesstoyournewhouse,youcangoinside,setup

housekeeping,paintit,cleanit,furnishit,removetrash,

landscapeit,whatever.Butbeforeyoucanreallydoanythingin

oraroundyourhouse,youmustbuildit.Lateryoumaywantto

addanewroom,showitforsale,demolishit,etc.Sinceyou

havetheblueprints,youcouldfindanotherpieceofproperty

andbuildahousejustlikeyours,maybepaintitadifferent

color,changethelandscaping,etc.Infact,youcouldbuilda

wholedevelopmentwithhouseslikeyoursfromthesame

design,eachhouseidentifiedbyitsuniqueaddress.

Inanobject-orientedlanguage,thehousewouldbetheobject,

anoun.Thestyle,numberofrooms,type,etc.,wouldbethe

propertiesthatdescribetheobject,likeadjectives,andthe

verbs,suchaspaintthehouse,moveintothehouse,showthe

house,describethe"behaviors"fortheobject.

Allofthiswillbecomeclearerasweexamineanumberof

examplesanddiscusshowPerlcreates,maniuplates,and

destroysobjects.



14.2.2.TheSteps

Thischapterwilldiscussanumberoftopicsindetail.Forthebig

picture,thefollowingstepsarenecessarytocreatethenew

datatypecalledobjectanddefinewhatitcando:

1. Determinewhatyourobjectisandwhatitissupposedto

accomplish(design).



2. Createthenewobject(constructor)inapackage,calleda

class.

3. Describetheobject;i.e.,giveitproperties,attributes

(adjectives).

4. Blesstheobject(makethedatatypeanobject).

5. Definethefunctions(verbs),whatitcandoorwhatcanbe

donetoit(methods).

6. Usetheobject(definetheuserinterface,callthemethods).

7. Reusetheobject(inheritance).

8. Destroytheobject(removetheobjectfrommemory).



14.2.3.ClassesandPrivacy

APerlclassisjustapackage.Thetermsareinterchangeable.A

classisstoredina.pmmodule,andtheclassnameisthesame

asthemodule(minusthe.pmextension).Ifyouwantto

distinguishbetweenthetwoterms,aclassisapackage

containingspecialsubroutinescalledmethodsthatmanipulate

objects.APerlclassnormallyconsistsof:

1. Thedatathatdescribestheobject.

2. Afunction,called"bless,"thatcreatestheobject.

3. Specialsubroutines,called"methods,"thatknowhowto

create,access,manipulate,anddestroytheobject.

Figure14.1.Whatmakesupaclass?The.pmfile.



Sinceaclassisreallyjustapackage,ithasitsownsymbol

table,andthedataorroutinesinoneclasscanbeaccessedin

anotherviathedoublecolon(Perl5)orthesingleapostrophe

(Perl4).

Unlikeotherlanguages,Perldoesnotstrictlymonitor

public/privateborderswithinitsmodules.[2]Tokeepvariables

private,themyfunctionisused.Themyvariablesexistonly

withintheinnermostenclosingblock,subroutine,eval,orfile.

Themyvariablescannotbeaccessedfromanotherpackageby

usingthedoublecolon(orsingleapostrophe),becausemy

variablesarenotrelatedtoanypackage;theyarenotstoredin

thesymboltableofthepackageinwhichtheyarecreated.

[2]Wall,L.,andSchwartz,R.L.,ProgrammingPerl,2nded.,O'Reilly&



Associates:Sebastopol,CA,1998,p.287.



Example14.1.

#!/bin/perl

1packagemain;

2$name="Susan";



3my$birthyear=1942;

4packagenosy;

5print"Hello$main::name.\n";

6print"Youwerebornin$main::birthyear?\n";

(Output)

5HelloSusan.

6Youwerebornin?



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

Chapter 14. Bless Those Things! (Object-Oriented Perl)

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

×