Commit 810e5dd139b8eb331f1ed9c8d4eb6f1bd2aa342b

Merge branch 'master' of git://gitorious.org/squeak-by-example/tsilva-clone

Commit diff

PortugueseBook/Model/Model.tex

 
260260\end{code}
261261%FIXME: termos sem acento! sessão "code" não aceita unicode ou 'latex escapes'
262262
263Você define uma classe preenchendo o template oferecido no \subind{system browser}{lado da instância}.
264Quando você aceita este template, o sistema cria não só a classe que você definiu, como também
263Você define uma classe preenchendo o modelo oferecido no \subind{system browser}{lado da instância}.
264Quando você aceita este modelo, o sistema cria não só a classe que você definiu, como também
265265a metaclasse correspondente.
266266Você pode navegar na metaclasse clicando no botão \button{class}.
267A única parte do template de criação da metaclasse que faz sentido para você editar diretamente
267A única parte do modelo de criação da metaclasse que faz sentido para você editar diretamente
268268é a lista de nomes de variáveis de instância.
269269
270270Uma vez que a classe foi criada, clicando no botão \button{instance} você poderá editar e navegar
384384todas as subclasses e todas as suas instâncias compartilham a mesma variável estática.
385385
386386
387\paragraph{Example: Defining a Singleton.}
388The \ind{Singleton pattern}~\cite{Alpe98a} provides a typical example of the use of class instance variables and class methods.
389Imagine that we would like to implement a class \ct{WebServer} and use the Singleton pattern to ensure that it has only one instance.
387\paragraph{Exemplo: Definindo um \emph{Singleton}.}
388O padrão \emph{Singleton}~\cite{Alpe98a} oferece um exemplo típico de uso de variáveis de instância de classe
389e métodos de classe. Imagine que nós queremos implementar uma classe \ct{WebServer} e usar o padrão
390Singleton para assegurar que ela tem apenas uma instância.
390391
391Clicking on the \button{instance} button in the browser, we define the class \clsind{WebServer} as follows (\clsref{singleton}).
392Clicando no botão \button{instance} no browser, nós definimos a classe \clsind{WebServer} como
393se segue (\clsref{singleton}).
392394
393\begin{classdef}[singleton]{A singleton class}
395\begin{classdef}[singleton]{Uma classe singleton}
394396Object subclass: #WebServer
395397 instanceVariableNames: 'sessions'
396398 classVariableNames: ''
400400 category: 'Web'
401401\end{classdef}
402402
403Then, clicking on the \button{class} button, we add the instance variable \ct{uniqueInstance} to the \subind{system browser}{class side}.
403Então, clicando no botão \button{class}, nós adicionamos a variável de instância \ct{uniqueInstance}
404no \subind{system browser}{lado da classe}.
404405
405\begin{classdef}[webserver]{The class side of the singleton class}
406\begin{classdef}[webserver]{O lado da classe da classe singleton}
406407WebServer class
407408 instanceVariableNames: 'uniqueInstance'
408409\end{classdef}
409410
410The consequence of this is that the class \ct{WebServer} now has another instance variable,
411in addition to the variables that it inherits, such as \ct{superclass} and \ct{methodDict}.
411A consequência disso é que a classe \ct{WebServer} agora tem outra variável de instância,
412além das variáveis que ela herda, tal como \ct{superclass} e \ct{methodDict}.
412413
413We can now define a class \subind{class}{method} named \ct{uniqueInstance} as shown in \mthref{uniqueInstance}.
414This method first checks whether \ct{uniqueInstance} has been initialized.
415If it has not, the method creates an instance and assigns it to the class instance variable \ct{uniqueInstance}.
416Finally the value of \ct{uniqueInstance} is returned.
417Since \ct{uniqueInstance} is a class instance variable, this method can directly access it.
418
419\begin{method}[uniqueInstance]{uniqueInstance (on the class side)}
414Agora nós podemos definir um \subind{classe}{método} de classe chamado \ct{uniqueInstance} como
415mostrado em \mthref{uniqueInstance}.
416Este método primeiramente verifica se \ct{uniqueInstance} foi inicializada.
417Se não foi, o método cria uma instância e atribui ela à variável de instância de classe \ct{uniqueInstance}.
418Finalmente, o valor de \ct{uniqueInstace} é retornado.
419Uma vez que \ct{uniqueInstace} é uma variável de instância de classe, este método pode acessá-la diretamente.
420
421\begin{method}[uniqueInstance]{uniqueInstance (no lado da classe)}
420422WebServer class>>>uniqueInstance
421423 uniqueInstance ifNil: [uniqueInstance := self new].
422424 ^ uniqueInstance
423425\end{method}
424426
425The first time that \ct{WebServer uniqueInstance} is executed, an instance of the class \ct{WebServer} will be created and assigned to the \ct{uniqueInstance} variable.
426The next time, the previously created instance will be returned instead of creating a new one.
427A primeira vez que \ct{WebServer uniqueInstance} é executada, uma instância da classe \ct{WebServer}
428será criada e atribuída à variável \ct{uniqueInstance}.
429Na próxima vez, a instância anteriormente criada será retornada ao invés de novas instâncias serem criadas.
427430
428Note that the instance creation code inside the conditional in \mthref{uniqueInstance} is written as \ct{self new} and not as \ct{WebServer new}.
429What is the difference? Since the \ct{uniqueInstance} method is defined in \ct{WebServer class}, you might think that they were the same. And indeed, until someone creates a subclass of \ct{WebServer}, they are the same. But suppose that \ct{ReliableWebServer} is a subclass of \ct{WebServer}, and inherits the \ct{uniqueInstance} method. We would clearly expect \ct{ReliableWebServer uniqueInstance} to answer a \lct{ReliableWebServer}:. Using \self ensures that this will happen, since it will be bound to the respective class.
430Note also that \ct{WebServer} and \ct{ReliableWebServer} will each have their own class instance variable called \ct{uniqueInstance}. These two variables will of course have different values.
431Note que o código da criação de instância dentro da condicional em \mthref{uniqueInstance} está
432escrita como \ct{self new} e não como \ct{WebServer new}.
433Qual a diferença? Já que o método \ct{uniqueInstance} está definido em \ct{WebServer class}, você pode pensar que elas são a mesma. E, de fato, até que alguém crie uma subclasse de \ct{WebServer}, elas são a mesma.
434Mas, suponha que \ct{ReliableWebServer} seja uma subclasse de \ct{WebServer}, e herda o método \ct{uniqueInstance}. Nós certamente esperaríamos que \ct{ReliableWebServer uniqueInstance} respondesse uma
435\lct{ReliableWebServer}:. O uso de \self assegura que isto irá acontecer, uma vez que este será associado
436à respectiva classe.
437Note também que \ct{WebServer} e \ct{ReliableWebServer} terão, cada uma, sua própria variável de instância de classe chamada \ct{uniqueInstance}. Estas duas variáveis terão, obviamente, valores diferentes.
431438
432439%=========================================================
433\section{Every class has a superclass}
440\section{Toda classe tem uma superclasse}
434441
435442%\ruleref{inheritance}
436443
437Each class in \st inherits its behaviour and the description of its structure from a single \emphind{superclass}.
438This means that \st has single \ind{inheritance}.
444Cada classe do \st herda seu comportamento e descrição de sua estrutura de uma única \emphind{superclass}.
445Isso significa que o \st tem \ind{herança} singular.
439446
440447\needlines{2}
441448\begin{code}{@TEST}
454454ProtoObject superclass --> nil
455455\end{code}
456456
457Traditionally the root of the \st inheritance hierarchy is the class \clsind{Object} (since everything is an object).
458In \squeak, the root is actually a class called \clsind{ProtoObject}, but you will normally not pay any attention to this class.
459\ct{ProtoObject} encapsulates the minimal set of messages that all objects \emph{must} have. However, most classes inherit from \ct{Object}, which defines many additional messages that almost all objects ought to understand and respond to.
460Unless you have a very good reason to do otherwise, when creating application classes you should normally subclass \ct{Object}, or one of its subclasses.
461
462\dothis{A new class is normally created by sending the message
463\ct{subclass: instanceVariableNames: ...}
464to an existing class.
465There are a few other methods to create classes.
466Have a look at the protocol \prot{Kernel-Classes \go Class \go subclass creation} to see what they are.}
457Tradicionalmente, a raiz da hierarquia de herança no \st é a classe \clsind{Object} (uma vez que
458tudo é objeto).
459No \squeak, a raiz é, na verdade, a classe chamada \clsind{ProtoObject} mas, normalmente, você não irá
460se preocupar com esta classe.
461\ct{ProtoObject} encapsula o conjunto mónimo de mensagens que um objeto \emph{deve} ter. Porém,
462a maior parte das classes herda de \ct{Object}, que define muitas mensagens adicionais que quase
463todos os objetos deve entender e responder.
464A não ser que você tenha um motivo muito bom para fazer o contrário, quando criar classes de aplicação
465normalmente você deve herdar de \ct{Object} ou uma de suas subclasses.
466
467\dothis{Uma nova classe normalmente é criada enviando a mensagem \ct{subclass: instanceVariableNames: ...}
468para uma classe existente.
469Existem outros (poucos) métodos para criar classes. Procure no protocolo
470\prot{Kernel-Classes \go Class \go subclass creation} para ver quais são.}
467471\scatindex{Kernel-Classes}
468\protindex{creation}
472\protindex{criação}
469473
470474%There is no special syntax for creating abstract classes in \st.
471475%An abstract class is an ordinary class in which the implementation of some methods is deferred to a subclass.
472476%This is repeated in the next section
473477
474Although \squeak does not provide multiple inheritance, since version 3.9 it has incorporated a mechanism called \emphind{trait}{}s for sharing behaviour across unrelated classes.
475Traits are collections of methods that can be reused by multiple classes that are not related by inheritance. Using traits allows one to share code between different classes without duplicating code.
478Embora \squeak não ofereça herança múltipla, desde a versão 3.9 um mecanismo chamado \emphind{trait}{}s
479foi incorporado para compartilhar comportamento entre classes não relacionadas.
480Traits são coleções de métodos que podem ser reutilizados por múltiplas classes que não são relacionadas
481por herança. O uso de traits permite compartilhar código entre diferentes classes sem duplicar código.
476482
477483%---------------------------------------------------------
478\subsection{Abstract methods and abstract classes}
479
480An \subind{class}{abstract} class is a class that exists to be subclassed, rather than to be instantiated.
481An abstract class is usually incomplete, in the sense that it does not define all of the methods that it uses.
482The ``missing'' methods\,---\,those that the other methods assume, but which are not themselves defined\,---\,are called \subind{method}{abstract} methods.
483\seeindex{abstract class}{class, abstract}
484\seeindex{abstract method}{method, abstract}
485
486\st has no dedicated syntax to specify that a method or a class is abstract.
487By convention, the body of an abstract method consists of the expression \mbox{\ct{self subclassResponsibility}.}
488This is known as a ``marker method'', and indicates that subclasses have the responsibility to define a concrete version of the method.
489\ct{self subclassResponsibility} methods should always be overridden, and thus should never be executed.
490If you forget to override one, and it is executed, an exception will be raised.
484\subsection{Métodos abstratos e classes abstratas}
485
486Uma classe \subind{classe}{abstrata} é uma classe que existe apenas para ser herdada, e não, instanciada.
487Uma classe abstrata, em geral, é incompleta pois não define todos os métodos que ela utiliza.
488Os métodos ``indefinidos''\,---\,aqueles que outros métodos assumem existir, mas que não estão definidos\,---\,
489são chamados métodos \subind{método}{abstrato}s.
490\seeindex{classe abstrata}{classe, abstrata}
491\seeindex{método abstrato}{método, abstrato}
492
493\st não tem uma sintaxe específica para informar que um método ou uma classe são abstratos.
494Por convenção, o corpo de um método abstrato consiste da expressão \mbox{\ct{self subclassResponsibility}.}
495Isso é conhecido como um ``método marcado'' \footnote{marker method} e indica que as subclasses
496têm a responsabilidade de definir uma versão concreta do método.
497Métodos \ct{self subclassResponsibility} sempre devem ser sobreescritos e, portanto, nunca devem ser executados.
498Se você esquecer de sobreescrever um deles, e ele for executado, uma exceção serão lançada.
491499\cmindex{Object}{subclassResponsibility}
492500
493A class is considered abstract if one of its methods is abstract.
494Nothing actually prevents you from creating an instance of an abstract class; everything will work until an abstract method is invoked.
501Uma classe é considerada abstrata se um de seus métodos for abstrato.
502Nada impede que você crie uma instância de uma classe abstrata; tudo funcionará até que métodos abstratos
503sejam invocados.
495504
496\subsubsection{Example: the class \ct{Magnitude}.}
497\clsind{Magnitude} is an abstract class that helps us to define objects that can be compared to each other. Subclasses of \ct{Magnitude} should implement the methods \ct{<}, \ct{=} and \ct{hash}. Using such messages \ct{Magnitude} defines other methods such as \ct{>}, \ct{>=}, \ct{<=}, \ct{max:}, \ct{min:} \ct{between:and:} and others for comparing objects. Such methods are inherited by subclasses. The method \mthind{Magnitude}{<} is abstract and defined as shown in \mthref{MagnitudeLessThan}.
505\subsubsection{Examplo: a classe \ct{Magnitude}.}
506\clsind{Magnitude} é uma classe abstrata que nos ajuda a definir objetos que podem ser comparados com outros objetos.
507Subclasses de \ct{Magnitude} devem implementar os métodos \ct{<}, \ct{=} e \ct{hash}. Usando tais mensagens,
508\ct{Magnitude} define outros métodos como \ct{>}, \ct{>=}, \ct{<=}, \ct{max:}, \ct{min:} \ct{between:and:}
509e outros para comparar objetos. Estes mpetodos são herdados pelas subclasses. O método \mthind{Magnitude}{<}
510é abstrato e sua definição é ilustrada em \mthref{MagnitudeLessThan}.
498511
499512\begin{method}[MagnitudeLessThan]{\ct{Magnitude>>><}}
500513Magnitude>>>< aMagnitude
501 "Answer whether the receiver is less than the argument."
514 "Responde se o receptor e menor que o argumento."
502515 ^self subclassResponsibility
503516\end{method}
517%FIXME: comentário sem acento (... receptor é ...)
504518
505519\noindent
506By contrast, the method \mthind{Magnitude}{>=} is concrete; it is defined in terms of \ct{<}:
520Em contraste, o método \mthind{Magnitude}{>=} é concreto; ele é definido em termos de \ct{<}:
507521
508522\begin{method}[Magnitude>=]{\ct{Magnitude>>>>=}}
509523>= aMagnitude
510 "Answer whether the receiver is greater than or equal to the argument."
524 "Responde se o receptor e maior ou igual ao argumento."
511525 ^(self < aMagnitude) not
512526\end{method}
513The same is true of the other comparison methods.
527%FIXME: comentário sem acento (... receptor é ...)
528O mesmo é verdadeiro para outros métodos de comparação.
514529
515\clsind{Character} is a subclass of \ct{Magnitude}; it overrides the \mthind{Object}{subclassResponsibility} method for \ct{<} with its own version of \ct{<} (see \mthref{CharacterLessThan}). \ct{Character} also defines methods \ct{=} and \ct{hash}; it inherits from \ct{Magnitude} the methods \ct{>=}, \ct{<=}, \ct{~=} and others.
530A classe \clsind{Character} é uma subclasse de \ct{Magnitude}; ela sobreescrever o método
531\mthind{Object}{subclassResponsibility} por \ct{<} com sua própria versão de \ct{<}
532(veja \mthref{CharacterLessThan}). \ct{Character} também define os métodos
533\ct{=} e \ct{hash}; ela herda de \ct{Magnitude} os métodos \ct{>=}, \ct{<=}, \ct{~=} e outros.
516534
517535\begin{method}[CharacterLessThan]{\ct{Character>>><}}
518536Character>>>< aCharacter
519 "Answer true if the receiver's value < aCharacter's value."
537 "Responde true se o valor do receptor < o valor de aCharacter."
520538 ^self asciiValue < aCharacter asciiValue
521539\end{method}
540%FIXME: comentário sem acento (... receptor é ...)
522541
523542%---------------------------------------------------------
524543\subsection{Traits}
525A \emphind{trait} is a collection of methods that can be included in the behaviour of a class without the need for inheritance.
526This makes it easy for classes to have a unique superclass, yet still share useful methods with otherwise unrelated classes.
544Um \emphind{trait} é uma coleção de métodos que podem ser incluídos no comportamento de uma classe
545sem precisar utilizar herança.
546Isso torna fácil o trabalho de compartilhar métodos úteis entre classes não relacionadas, mesmo
547que estas tenham apenas uma superclasse.
527548
528To define a new trait, simply replace the subclass creation template by a message to the class \clsind{Trait}.
549Para definir um novo trait, simplesmente troque o modelo de criação de subclasse por uma mensagem
550para a classe \clsind{Trait}.
529551
530552\needspace{5\baselineskip}
531\begin{classdef}[tauthor]{Defining a new trait}
553\begin{classdef}[tauthor]{Definindo um novo trait}
532554Trait named: #TAuthor
533555 uses: { }
534556 category: 'SBE-Quinto'
535557\end{classdef}
536558
537559\noindent
538Here we define the trait \ct{TAuthor} in the category \scat{SBE-Quinto}.
539This trait does not \emph{use} any other existing traits.
540In general we can specify a \emph{trait composition expression} of other traits to use as part of the \ct{uses:} keyword argument.
541Here we simply provide an empty array.
560Aqui nós definimos o trait \ct{TAuthor} na categoria \scat{SBE-Quinto}.
561Este trait não \emph{usa} nenhum outro trait existente.
562Em geral, nós podemos especificar uma \emph{expressão de composição de traits} \footnote{trait composition expression} de outros traits para usar como parte do argumento \ct{uses:}.
563Aqui nós oferecemos apenas um array vazio.
542564
543Traits may contain methods, but no instance variables.
544Suppose we would like to be able to add an \ct{author} method to various classes, independent of where they occur in the hierarchy.
545We might do this as follows:
565Traits podem conter métodos, mas não contém variáveis de instância.
566Suponha que nós queremos adicionar um método \ct{author} à várias classes, independente de
567onde elas se encontram na hierarquia.
568Nós poderiamos fazer o seguinte:
546569
547\begin{method}[author]{An author method}
570\begin{method}[author]{Um método author}
548571TAuthor>>>author
549 "Returns author initials"
572 "Retorna as iniciais do autor"
550573 ^ 'on' "oscar nierstrasz"
551574\end{method}
552575
553576\noindent
554Now we can use this trait in a class that already has its own superclass, for instance the \ct{SBEGame} class that we defined in \charef{firstApp}.
555We simply modify the class creation template for \ct{SBEGame} to include a \ct{uses:} keyword argument that specifies that \ct{TAuthor} should be used.
577Agora nós podemos utilizar esta trait em uma classe que já tenha sua própria superclasse,
578por exemplo, a classe \ct{SBEGame} que definimos no \charef{firstApp}.
579Nós simplesmente modificamos o modelo de criação de classe pelo \ct{SBEGame} para incluir o
580argumento \ct{uses:} especificando que \ct{TAuthor} deve ser utilizado.
556581
557\begin{classdef}[sbegamewithtrait]{Using a trait}
582\begin{classdef}[sbegamewithtrait]{Usando um trait}
558583BorderedMorph subclass: #SBEGame
559584 uses: TAuthor
560585 instanceVariableNames: 'cells'
588588 category: 'SBE-Quinto'
589589\end{classdef}
590590
591If we now instantiate \ct{SBEGame}, it will respond to the \ct{author} message as expected.
591Se nós instanciarmos um \ct{SBEGame}, o objeto responderá à mensagem \ct{author} como esperado.
592592
593593\begin{code}{}
594594SBEGame new author --> 'on'
595595\end{code}
596596
597Trait composition expressions may combine multiple traits using the \ct{+} operator.
598In case of conflicts (\ie if multiple traits define methods with the same name), these conflicts can be resolved by explicitly removing these methods (with \ct{-}), or by redefining these methods in the class or trait that you are defining.
599It is also possible to \emph{alias} methods (with \ct{@}), providing a new name for them.
597Expressões de composição de traits podem combinar múltiplas traits utilizando o operador \ct{+}.
598Em caso de conflito (isso é, se várias traits definem métodos com o mesmo nome), estes conflitos
599podem ser resolvidos explicitamente removendo estes métodos (com \ct{-}), ou redefinindo estes métodos
600na classe ou trait que você está criando.
601Também é possível \emph{apelidar} métodos (com \ct{@}), informando um novo nome para eles.
600602
601Traits are used in the system kernel.
602One good example is the class \clsind{Behavior}.
603Os traits são utiliados no núcleo do sistema. Um bom exemplo é a classe \clsind{Behavior}
603604
604605\needlines{8}
605\begin{classdef}[behaviorwithtraits]{\ct{Behavior} defined using traits}
606\begin{classdef}[behaviorwithtraits]{\ct{Behavior} definida utilizando traits}
606607Object subclass: #Behavior
607608 uses: TPureBehavior @ {#basicAddTraitSelector:withMethod:->#addTraitSelector:withMethod:}
608609 instanceVariableNames: 'superclass methodDict format'
612612 category: 'Kernel-Classes'
613613\end{classdef}
614614\noindent
615Here we see that the method \ct{addTraitSelector:withMethod:} defined in the trait \ct{TPureBehavior} has been aliased to \ct{basicAddTraitSelector:withMethod:}.
616Support for traits is currently being added to the browsers.
615Aqui nós vemos que o método \ct{addTraitSelector:withMethod:} definido na trait \ct{TPureBehavior}
616foi apelidado para \ct{basicAddTraitSelector:withMethod:}.
617Suporte à traits está sendo adicionado aos browsers atualmente.
617618
618619%=========================================================
619620\section{Everything happens by message sending}
toggle raw diff