| |   |
| 260 | 260 | \end{code} |
| 261 | 261 | %FIXME: termos sem acento! sessão "code" não aceita unicode ou 'latex escapes' |
| 262 | 262 | |
| 263 | | Você define uma classe preenchendo o template oferecido no \subind{system browser}{lado da instância}. |
| 264 | | Quando você aceita este template, o sistema cria não só a classe que você definiu, como também |
| 263 | Você define uma classe preenchendo o modelo oferecido no \subind{system browser}{lado da instância}. |
| 264 | Quando você aceita este modelo, o sistema cria não só a classe que você definiu, como também |
| 265 | 265 | a metaclasse correspondente. |
| 266 | 266 | Você pode navegar na metaclasse clicando no botão \button{class}. |
| 267 | | A única parte do template de criação da metaclasse que faz sentido para você editar diretamente |
| 267 | A única parte do modelo de criação da metaclasse que faz sentido para você editar diretamente |
| 268 | 268 | é a lista de nomes de variáveis de instância. |
| 269 | 269 | |
| 270 | 270 | Uma vez que a classe foi criada, clicando no botão \button{instance} você poderá editar e navegar |
| … | … | |
| 384 | 384 | todas as subclasses e todas as suas instâncias compartilham a mesma variável estática. |
| 385 | 385 | |
| 386 | 386 | |
| 387 | | \paragraph{Example: Defining a Singleton.} |
| 388 | | The \ind{Singleton pattern}~\cite{Alpe98a} provides a typical example of the use of class instance variables and class methods. |
| 389 | | Imagine 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}.} |
| 388 | O padrão \emph{Singleton}~\cite{Alpe98a} oferece um exemplo típico de uso de variáveis de instância de classe |
| 389 | e métodos de classe. Imagine que nós queremos implementar uma classe \ct{WebServer} e usar o padrão |
| 390 | Singleton para assegurar que ela tem apenas uma instância. |
| 390 | 391 | |
| 391 | | Clicking on the \button{instance} button in the browser, we define the class \clsind{WebServer} as follows (\clsref{singleton}). |
| 392 | Clicando no botão \button{instance} no browser, nós definimos a classe \clsind{WebServer} como |
| 393 | se segue (\clsref{singleton}). |
| 392 | 394 | |
| 393 | | \begin{classdef}[singleton]{A singleton class} |
| 395 | \begin{classdef}[singleton]{Uma classe singleton} |
| 394 | 396 | Object subclass: #WebServer |
| 395 | 397 | instanceVariableNames: 'sessions' |
| 396 | 398 | classVariableNames: '' |
| … | … | |
| 400 | 400 | category: 'Web' |
| 401 | 401 | \end{classdef} |
| 402 | 402 | |
| 403 | | Then, clicking on the \button{class} button, we add the instance variable \ct{uniqueInstance} to the \subind{system browser}{class side}. |
| 403 | Então, clicando no botão \button{class}, nós adicionamos a variável de instância \ct{uniqueInstance} |
| 404 | no \subind{system browser}{lado da classe}. |
| 404 | 405 | |
| 405 | | \begin{classdef}[webserver]{The class side of the singleton class} |
| 406 | \begin{classdef}[webserver]{O lado da classe da classe singleton} |
| 406 | 407 | WebServer class |
| 407 | 408 | instanceVariableNames: 'uniqueInstance' |
| 408 | 409 | \end{classdef} |
| 409 | 410 | |
| 410 | | The consequence of this is that the class \ct{WebServer} now has another instance variable, |
| 411 | | in addition to the variables that it inherits, such as \ct{superclass} and \ct{methodDict}. |
| 411 | A consequência disso é que a classe \ct{WebServer} agora tem outra variável de instância, |
| 412 | além das variáveis que ela herda, tal como \ct{superclass} e \ct{methodDict}. |
| 412 | 413 | |
| 413 | | We can now define a class \subind{class}{method} named \ct{uniqueInstance} as shown in \mthref{uniqueInstance}. |
| 414 | | This method first checks whether \ct{uniqueInstance} has been initialized. |
| 415 | | If it has not, the method creates an instance and assigns it to the class instance variable \ct{uniqueInstance}. |
| 416 | | Finally the value of \ct{uniqueInstance} is returned. |
| 417 | | Since \ct{uniqueInstance} is a class instance variable, this method can directly access it. |
| 418 | | |
| 419 | | \begin{method}[uniqueInstance]{uniqueInstance (on the class side)} |
| 414 | Agora nós podemos definir um \subind{classe}{método} de classe chamado \ct{uniqueInstance} como |
| 415 | mostrado em \mthref{uniqueInstance}. |
| 416 | Este método primeiramente verifica se \ct{uniqueInstance} foi inicializada. |
| 417 | Se não foi, o método cria uma instância e atribui ela à variável de instância de classe \ct{uniqueInstance}. |
| 418 | Finalmente, o valor de \ct{uniqueInstace} é retornado. |
| 419 | Uma 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)} |
| 420 | 422 | WebServer class>>>uniqueInstance |
| 421 | 423 | uniqueInstance ifNil: [uniqueInstance := self new]. |
| 422 | 424 | ^ uniqueInstance |
| 423 | 425 | \end{method} |
| 424 | 426 | |
| 425 | | The 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. |
| 426 | | The next time, the previously created instance will be returned instead of creating a new one. |
| 427 | A primeira vez que \ct{WebServer uniqueInstance} é executada, uma instância da classe \ct{WebServer} |
| 428 | será criada e atribuída à variável \ct{uniqueInstance}. |
| 429 | Na próxima vez, a instância anteriormente criada será retornada ao invés de novas instâncias serem criadas. |
| 427 | 430 | |
| 428 | | Note that the instance creation code inside the conditional in \mthref{uniqueInstance} is written as \ct{self new} and not as \ct{WebServer new}. |
| 429 | | What 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. |
| 430 | | Note 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. |
| 431 | Note que o código da criação de instância dentro da condicional em \mthref{uniqueInstance} está |
| 432 | escrita como \ct{self new} e não como \ct{WebServer new}. |
| 433 | Qual 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. |
| 434 | Mas, 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. |
| 437 | Note 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. |
| 431 | 438 | |
| 432 | 439 | %========================================================= |
| 433 | | \section{Every class has a superclass} |
| 440 | \section{Toda classe tem uma superclasse} |
| 434 | 441 | |
| 435 | 442 | %\ruleref{inheritance} |
| 436 | 443 | |
| 437 | | Each class in \st inherits its behaviour and the description of its structure from a single \emphind{superclass}. |
| 438 | | This means that \st has single \ind{inheritance}. |
| 444 | Cada classe do \st herda seu comportamento e descrição de sua estrutura de uma única \emphind{superclass}. |
| 445 | Isso significa que o \st tem \ind{herança} singular. |
| 439 | 446 | |
| 440 | 447 | \needlines{2} |
| 441 | 448 | \begin{code}{@TEST} |
| … | … | |
| 454 | 454 | ProtoObject superclass --> nil |
| 455 | 455 | \end{code} |
| 456 | 456 | |
| 457 | | Traditionally the root of the \st inheritance hierarchy is the class \clsind{Object} (since everything is an object). |
| 458 | | In \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. |
| 460 | | Unless 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: ...} |
| 464 | | to an existing class. |
| 465 | | There are a few other methods to create classes. |
| 466 | | Have a look at the protocol \prot{Kernel-Classes \go Class \go subclass creation} to see what they are.} |
| 457 | Tradicionalmente, a raiz da hierarquia de herança no \st é a classe \clsind{Object} (uma vez que |
| 458 | tudo é objeto). |
| 459 | No \squeak, a raiz é, na verdade, a classe chamada \clsind{ProtoObject} mas, normalmente, você não irá |
| 460 | se preocupar com esta classe. |
| 461 | \ct{ProtoObject} encapsula o conjunto mónimo de mensagens que um objeto \emph{deve} ter. Porém, |
| 462 | a maior parte das classes herda de \ct{Object}, que define muitas mensagens adicionais que quase |
| 463 | todos os objetos deve entender e responder. |
| 464 | A não ser que você tenha um motivo muito bom para fazer o contrário, quando criar classes de aplicação |
| 465 | normalmente 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: ...} |
| 468 | para uma classe existente. |
| 469 | Existem outros (poucos) métodos para criar classes. Procure no protocolo |
| 470 | \prot{Kernel-Classes \go Class \go subclass creation} para ver quais são.} |
| 467 | 471 | \scatindex{Kernel-Classes} |
| 468 | | \protindex{creation} |
| 472 | \protindex{criação} |
| 469 | 473 | |
| 470 | 474 | %There is no special syntax for creating abstract classes in \st. |
| 471 | 475 | %An abstract class is an ordinary class in which the implementation of some methods is deferred to a subclass. |
| 472 | 476 | %This is repeated in the next section |
| 473 | 477 | |
| 474 | | Although \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. |
| 475 | | Traits 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. |
| 478 | Embora \squeak não ofereça herança múltipla, desde a versão 3.9 um mecanismo chamado \emphind{trait}{}s |
| 479 | foi incorporado para compartilhar comportamento entre classes não relacionadas. |
| 480 | Traits são coleções de métodos que podem ser reutilizados por múltiplas classes que não são relacionadas |
| 481 | por herança. O uso de traits permite compartilhar código entre diferentes classes sem duplicar código. |
| 476 | 482 | |
| 477 | 483 | %--------------------------------------------------------- |
| 478 | | \subsection{Abstract methods and abstract classes} |
| 479 | | |
| 480 | | An \subind{class}{abstract} class is a class that exists to be subclassed, rather than to be instantiated. |
| 481 | | An abstract class is usually incomplete, in the sense that it does not define all of the methods that it uses. |
| 482 | | The ``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. |
| 487 | | By convention, the body of an abstract method consists of the expression \mbox{\ct{self subclassResponsibility}.} |
| 488 | | This 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. |
| 490 | | If you forget to override one, and it is executed, an exception will be raised. |
| 484 | \subsection{Métodos abstratos e classes abstratas} |
| 485 | |
| 486 | Uma classe \subind{classe}{abstrata} é uma classe que existe apenas para ser herdada, e não, instanciada. |
| 487 | Uma classe abstrata, em geral, é incompleta pois não define todos os métodos que ela utiliza. |
| 488 | Os métodos ``indefinidos''\,---\,aqueles que outros métodos assumem existir, mas que não estão definidos\,---\, |
| 489 | sã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. |
| 494 | Por convenção, o corpo de um método abstrato consiste da expressão \mbox{\ct{self subclassResponsibility}.} |
| 495 | Isso é conhecido como um ``método marcado'' \footnote{marker method} e indica que as subclasses |
| 496 | têm a responsabilidade de definir uma versão concreta do método. |
| 497 | Métodos \ct{self subclassResponsibility} sempre devem ser sobreescritos e, portanto, nunca devem ser executados. |
| 498 | Se você esquecer de sobreescrever um deles, e ele for executado, uma exceção serão lançada. |
| 491 | 499 | \cmindex{Object}{subclassResponsibility} |
| 492 | 500 | |
| 493 | | A class is considered abstract if one of its methods is abstract. |
| 494 | | Nothing actually prevents you from creating an instance of an abstract class; everything will work until an abstract method is invoked. |
| 501 | Uma classe é considerada abstrata se um de seus métodos for abstrato. |
| 502 | Nada impede que você crie uma instância de uma classe abstrata; tudo funcionará até que métodos abstratos |
| 503 | sejam invocados. |
| 495 | 504 | |
| 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. |
| 507 | Subclasses 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:} |
| 509 | e 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}. |
| 498 | 511 | |
| 499 | 512 | \begin{method}[MagnitudeLessThan]{\ct{Magnitude>>><}} |
| 500 | 513 | Magnitude>>>< aMagnitude |
| 501 | | "Answer whether the receiver is less than the argument." |
| 514 | "Responde se o receptor e menor que o argumento." |
| 502 | 515 | ^self subclassResponsibility |
| 503 | 516 | \end{method} |
| 517 | %FIXME: comentário sem acento (... receptor é ...) |
| 504 | 518 | |
| 505 | 519 | \noindent |
| 506 | | By contrast, the method \mthind{Magnitude}{>=} is concrete; it is defined in terms of \ct{<}: |
| 520 | Em contraste, o método \mthind{Magnitude}{>=} é concreto; ele é definido em termos de \ct{<}: |
| 507 | 521 | |
| 508 | 522 | \begin{method}[Magnitude>=]{\ct{Magnitude>>>>=}} |
| 509 | 523 | >= 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." |
| 511 | 525 | ^(self < aMagnitude) not |
| 512 | 526 | \end{method} |
| 513 | | The same is true of the other comparison methods. |
| 527 | %FIXME: comentário sem acento (... receptor é ...) |
| 528 | O mesmo é verdadeiro para outros métodos de comparação. |
| 514 | 529 | |
| 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. |
| 530 | A 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. |
| 516 | 534 | |
| 517 | 535 | \begin{method}[CharacterLessThan]{\ct{Character>>><}} |
| 518 | 536 | Character>>>< aCharacter |
| 519 | | "Answer true if the receiver's value < aCharacter's value." |
| 537 | "Responde true se o valor do receptor < o valor de aCharacter." |
| 520 | 538 | ^self asciiValue < aCharacter asciiValue |
| 521 | 539 | \end{method} |
| 540 | %FIXME: comentário sem acento (... receptor é ...) |
| 522 | 541 | |
| 523 | 542 | %--------------------------------------------------------- |
| 524 | 543 | \subsection{Traits} |
| 525 | | A \emphind{trait} is a collection of methods that can be included in the behaviour of a class without the need for inheritance. |
| 526 | | This makes it easy for classes to have a unique superclass, yet still share useful methods with otherwise unrelated classes. |
| 544 | Um \emphind{trait} é uma coleção de métodos que podem ser incluídos no comportamento de uma classe |
| 545 | sem precisar utilizar herança. |
| 546 | Isso torna fácil o trabalho de compartilhar métodos úteis entre classes não relacionadas, mesmo |
| 547 | que estas tenham apenas uma superclasse. |
| 527 | 548 | |
| 528 | | To define a new trait, simply replace the subclass creation template by a message to the class \clsind{Trait}. |
| 549 | Para definir um novo trait, simplesmente troque o modelo de criação de subclasse por uma mensagem |
| 550 | para a classe \clsind{Trait}. |
| 529 | 551 | |
| 530 | 552 | \needspace{5\baselineskip} |
| 531 | | \begin{classdef}[tauthor]{Defining a new trait} |
| 553 | \begin{classdef}[tauthor]{Definindo um novo trait} |
| 532 | 554 | Trait named: #TAuthor |
| 533 | 555 | uses: { } |
| 534 | 556 | category: 'SBE-Quinto' |
| 535 | 557 | \end{classdef} |
| 536 | 558 | |
| 537 | 559 | \noindent |
| 538 | | Here we define the trait \ct{TAuthor} in the category \scat{SBE-Quinto}. |
| 539 | | This trait does not \emph{use} any other existing traits. |
| 540 | | In general we can specify a \emph{trait composition expression} of other traits to use as part of the \ct{uses:} keyword argument. |
| 541 | | Here we simply provide an empty array. |
| 560 | Aqui nós definimos o trait \ct{TAuthor} na categoria \scat{SBE-Quinto}. |
| 561 | Este trait não \emph{usa} nenhum outro trait existente. |
| 562 | Em 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:}. |
| 563 | Aqui nós oferecemos apenas um array vazio. |
| 542 | 564 | |
| 543 | | Traits may contain methods, but no instance variables. |
| 544 | | Suppose we would like to be able to add an \ct{author} method to various classes, independent of where they occur in the hierarchy. |
| 545 | | We might do this as follows: |
| 565 | Traits podem conter métodos, mas não contém variáveis de instância. |
| 566 | Suponha que nós queremos adicionar um método \ct{author} à várias classes, independente de |
| 567 | onde elas se encontram na hierarquia. |
| 568 | Nós poderiamos fazer o seguinte: |
| 546 | 569 | |
| 547 | | \begin{method}[author]{An author method} |
| 570 | \begin{method}[author]{Um método author} |
| 548 | 571 | TAuthor>>>author |
| 549 | | "Returns author initials" |
| 572 | "Retorna as iniciais do autor" |
| 550 | 573 | ^ 'on' "oscar nierstrasz" |
| 551 | 574 | \end{method} |
| 552 | 575 | |
| 553 | 576 | \noindent |
| 554 | | Now 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}. |
| 555 | | We simply modify the class creation template for \ct{SBEGame} to include a \ct{uses:} keyword argument that specifies that \ct{TAuthor} should be used. |
| 577 | Agora nós podemos utilizar esta trait em uma classe que já tenha sua própria superclasse, |
| 578 | por exemplo, a classe \ct{SBEGame} que definimos no \charef{firstApp}. |
| 579 | Nós simplesmente modificamos o modelo de criação de classe pelo \ct{SBEGame} para incluir o |
| 580 | argumento \ct{uses:} especificando que \ct{TAuthor} deve ser utilizado. |
| 556 | 581 | |
| 557 | | \begin{classdef}[sbegamewithtrait]{Using a trait} |
| 582 | \begin{classdef}[sbegamewithtrait]{Usando um trait} |
| 558 | 583 | BorderedMorph subclass: #SBEGame |
| 559 | 584 | uses: TAuthor |
| 560 | 585 | instanceVariableNames: 'cells' |
| … | … | |
| 588 | 588 | category: 'SBE-Quinto' |
| 589 | 589 | \end{classdef} |
| 590 | 590 | |
| 591 | | If we now instantiate \ct{SBEGame}, it will respond to the \ct{author} message as expected. |
| 591 | Se nós instanciarmos um \ct{SBEGame}, o objeto responderá à mensagem \ct{author} como esperado. |
| 592 | 592 | |
| 593 | 593 | \begin{code}{} |
| 594 | 594 | SBEGame new author --> 'on' |
| 595 | 595 | \end{code} |
| 596 | 596 | |
| 597 | | Trait composition expressions may combine multiple traits using the \ct{+} operator. |
| 598 | | In 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. |
| 599 | | It is also possible to \emph{alias} methods (with \ct{@}), providing a new name for them. |
| 597 | Expressões de composição de traits podem combinar múltiplas traits utilizando o operador \ct{+}. |
| 598 | Em caso de conflito (isso é, se várias traits definem métodos com o mesmo nome), estes conflitos |
| 599 | podem ser resolvidos explicitamente removendo estes métodos (com \ct{-}), ou redefinindo estes métodos |
| 600 | na classe ou trait que você está criando. |
| 601 | Também é possível \emph{apelidar} métodos (com \ct{@}), informando um novo nome para eles. |
| 600 | 602 | |
| 601 | | Traits are used in the system kernel. |
| 602 | | One good example is the class \clsind{Behavior}. |
| 603 | Os traits são utiliados no núcleo do sistema. Um bom exemplo é a classe \clsind{Behavior} |
| 603 | 604 | |
| 604 | 605 | \needlines{8} |
| 605 | | \begin{classdef}[behaviorwithtraits]{\ct{Behavior} defined using traits} |
| 606 | \begin{classdef}[behaviorwithtraits]{\ct{Behavior} definida utilizando traits} |
| 606 | 607 | Object subclass: #Behavior |
| 607 | 608 | uses: TPureBehavior @ {#basicAddTraitSelector:withMethod:->#addTraitSelector:withMethod:} |
| 608 | 609 | instanceVariableNames: 'superclass methodDict format' |
| … | … | |
| 612 | 612 | category: 'Kernel-Classes' |
| 613 | 613 | \end{classdef} |
| 614 | 614 | \noindent |
| 615 | | Here we see that the method \ct{addTraitSelector:withMethod:} defined in the trait \ct{TPureBehavior} has been aliased to \ct{basicAddTraitSelector:withMethod:}. |
| 616 | | Support for traits is currently being added to the browsers. |
| 615 | Aqui nós vemos que o método \ct{addTraitSelector:withMethod:} definido na trait \ct{TPureBehavior} |
| 616 | foi apelidado para \ct{basicAddTraitSelector:withMethod:}. |
| 617 | Suporte à traits está sendo adicionado aos browsers atualmente. |
| 617 | 618 | |
| 618 | 619 | %========================================================= |
| 619 | 620 | \section{Everything happens by message sending} |
| toggle raw diff |
--- a/PortugueseBook/Model/Model.tex
+++ b/PortugueseBook/Model/Model.tex
@@ -260,11 +260,11 @@ aColor blue --> 1.0 "Metodo de acesso blue, no lado da instancia"
\end{code}
%FIXME: termos sem acento! sessão "code" não aceita unicode ou 'latex escapes'
-Você define uma classe preenchendo o template oferecido no \subind{system browser}{lado da instância}.
-Quando você aceita este template, o sistema cria não só a classe que você definiu, como também
+Você define uma classe preenchendo o modelo oferecido no \subind{system browser}{lado da instância}.
+Quando você aceita este modelo, o sistema cria não só a classe que você definiu, como também
a metaclasse correspondente.
Você pode navegar na metaclasse clicando no botão \button{class}.
-A única parte do template de criação da metaclasse que faz sentido para você editar diretamente
+A única parte do modelo de criação da metaclasse que faz sentido para você editar diretamente
é a lista de nomes de variáveis de instância.
Uma vez que a classe foi criada, clicando no botão \button{instance} você poderá editar e navegar
@@ -384,13 +384,15 @@ mensagens de acesso para sua classe.
todas as subclasses e todas as suas instâncias compartilham a mesma variável estática.
-\paragraph{Example: Defining a Singleton.}
-The \ind{Singleton pattern}~\cite{Alpe98a} provides a typical example of the use of class instance variables and class methods.
-Imagine that we would like to implement a class \ct{WebServer} and use the Singleton pattern to ensure that it has only one instance.
+\paragraph{Exemplo: Definindo um \emph{Singleton}.}
+O padrão \emph{Singleton}~\cite{Alpe98a} oferece um exemplo típico de uso de variáveis de instância de classe
+e métodos de classe. Imagine que nós queremos implementar uma classe \ct{WebServer} e usar o padrão
+Singleton para assegurar que ela tem apenas uma instância.
-Clicking on the \button{instance} button in the browser, we define the class \clsind{WebServer} as follows (\clsref{singleton}).
+Clicando no botão \button{instance} no browser, nós definimos a classe \clsind{WebServer} como
+se segue (\clsref{singleton}).
-\begin{classdef}[singleton]{A singleton class}
+\begin{classdef}[singleton]{Uma classe singleton}
Object subclass: #WebServer
instanceVariableNames: 'sessions'
classVariableNames: ''
@@ -398,42 +400,49 @@ Object subclass: #WebServer
category: 'Web'
\end{classdef}
-Then, clicking on the \button{class} button, we add the instance variable \ct{uniqueInstance} to the \subind{system browser}{class side}.
+Então, clicando no botão \button{class}, nós adicionamos a variável de instância \ct{uniqueInstance}
+no \subind{system browser}{lado da classe}.
-\begin{classdef}[webserver]{The class side of the singleton class}
+\begin{classdef}[webserver]{O lado da classe da classe singleton}
WebServer class
instanceVariableNames: 'uniqueInstance'
\end{classdef}
-The consequence of this is that the class \ct{WebServer} now has another instance variable,
-in addition to the variables that it inherits, such as \ct{superclass} and \ct{methodDict}.
+A consequência disso é que a classe \ct{WebServer} agora tem outra variável de instância,
+além das variáveis que ela herda, tal como \ct{superclass} e \ct{methodDict}.
-We can now define a class \subind{class}{method} named \ct{uniqueInstance} as shown in \mthref{uniqueInstance}.
-This method first checks whether \ct{uniqueInstance} has been initialized.
-If it has not, the method creates an instance and assigns it to the class instance variable \ct{uniqueInstance}.
-Finally the value of \ct{uniqueInstance} is returned.
-Since \ct{uniqueInstance} is a class instance variable, this method can directly access it.
-
-\begin{method}[uniqueInstance]{uniqueInstance (on the class side)}
+Agora nós podemos definir um \subind{classe}{método} de classe chamado \ct{uniqueInstance} como
+mostrado em \mthref{uniqueInstance}.
+Este método primeiramente verifica se \ct{uniqueInstance} foi inicializada.
+Se não foi, o método cria uma instância e atribui ela à variável de instância de classe \ct{uniqueInstance}.
+Finalmente, o valor de \ct{uniqueInstace} é retornado.
+Uma vez que \ct{uniqueInstace} é uma variável de instância de classe, este método pode acessá-la diretamente.
+
+\begin{method}[uniqueInstance]{uniqueInstance (no lado da classe)}
WebServer class>>>uniqueInstance
uniqueInstance ifNil: [uniqueInstance := self new].
^ uniqueInstance
\end{method}
-The 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.
-The next time, the previously created instance will be returned instead of creating a new one.
+A primeira vez que \ct{WebServer uniqueInstance} é executada, uma instância da classe \ct{WebServer}
+será criada e atribuída à variável \ct{uniqueInstance}.
+Na próxima vez, a instância anteriormente criada será retornada ao invés de novas instâncias serem criadas.
-Note that the instance creation code inside the conditional in \mthref{uniqueInstance} is written as \ct{self new} and not as \ct{WebServer new}.
-What 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.
-Note 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.
+Note que o código da criação de instância dentro da condicional em \mthref{uniqueInstance} está
+escrita como \ct{self new} e não como \ct{WebServer new}.
+Qual 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.
+Mas, 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
+\lct{ReliableWebServer}:. O uso de \self assegura que isto irá acontecer, uma vez que este será associado
+à respectiva classe.
+Note 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.
%=========================================================
-\section{Every class has a superclass}
+\section{Toda classe tem uma superclasse}
%\ruleref{inheritance}
-Each class in \st inherits its behaviour and the description of its structure from a single \emphind{superclass}.
-This means that \st has single \ind{inheritance}.
+Cada classe do \st herda seu comportamento e descrição de sua estrutura de uma única \emphind{superclass}.
+Isso significa que o \st tem \ind{herança} singular.
\needlines{2}
\begin{code}{@TEST}
@@ -445,107 +454,132 @@ Object superclass --> ProtoObject
ProtoObject superclass --> nil
\end{code}
-Traditionally the root of the \st inheritance hierarchy is the class \clsind{Object} (since everything is an object).
-In \squeak, the root is actually a class called \clsind{ProtoObject}, but you will normally not pay any attention to this class.
-\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.
-Unless you have a very good reason to do otherwise, when creating application classes you should normally subclass \ct{Object}, or one of its subclasses.
-
-\dothis{A new class is normally created by sending the message
-\ct{subclass: instanceVariableNames: ...}
-to an existing class.
-There are a few other methods to create classes.
-Have a look at the protocol \prot{Kernel-Classes \go Class \go subclass creation} to see what they are.}
+Tradicionalmente, a raiz da hierarquia de herança no \st é a classe \clsind{Object} (uma vez que
+tudo é objeto).
+No \squeak, a raiz é, na verdade, a classe chamada \clsind{ProtoObject} mas, normalmente, você não irá
+se preocupar com esta classe.
+\ct{ProtoObject} encapsula o conjunto mónimo de mensagens que um objeto \emph{deve} ter. Porém,
+a maior parte das classes herda de \ct{Object}, que define muitas mensagens adicionais que quase
+todos os objetos deve entender e responder.
+A não ser que você tenha um motivo muito bom para fazer o contrário, quando criar classes de aplicação
+normalmente você deve herdar de \ct{Object} ou uma de suas subclasses.
+
+\dothis{Uma nova classe normalmente é criada enviando a mensagem \ct{subclass: instanceVariableNames: ...}
+para uma classe existente.
+Existem outros (poucos) métodos para criar classes. Procure no protocolo
+\prot{Kernel-Classes \go Class \go subclass creation} para ver quais são.}
\scatindex{Kernel-Classes}
-\protindex{creation}
+\protindex{criação}
%There is no special syntax for creating abstract classes in \st.
%An abstract class is an ordinary class in which the implementation of some methods is deferred to a subclass.
%This is repeated in the next section
-Although \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.
-Traits 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.
+Embora \squeak não ofereça herança múltipla, desde a versão 3.9 um mecanismo chamado \emphind{trait}{}s
+foi incorporado para compartilhar comportamento entre classes não relacionadas.
+Traits são coleções de métodos que podem ser reutilizados por múltiplas classes que não são relacionadas
+por herança. O uso de traits permite compartilhar código entre diferentes classes sem duplicar código.
%---------------------------------------------------------
-\subsection{Abstract methods and abstract classes}
-
-An \subind{class}{abstract} class is a class that exists to be subclassed, rather than to be instantiated.
-An abstract class is usually incomplete, in the sense that it does not define all of the methods that it uses.
-The ``missing'' methods\,---\,those that the other methods assume, but which are not themselves defined\,---\,are called \subind{method}{abstract} methods.
-\seeindex{abstract class}{class, abstract}
-\seeindex{abstract method}{method, abstract}
-
-\st has no dedicated syntax to specify that a method or a class is abstract.
-By convention, the body of an abstract method consists of the expression \mbox{\ct{self subclassResponsibility}.}
-This is known as a ``marker method'', and indicates that subclasses have the responsibility to define a concrete version of the method.
-\ct{self subclassResponsibility} methods should always be overridden, and thus should never be executed.
-If you forget to override one, and it is executed, an exception will be raised.
+\subsection{Métodos abstratos e classes abstratas}
+
+Uma classe \subind{classe}{abstrata} é uma classe que existe apenas para ser herdada, e não, instanciada.
+Uma classe abstrata, em geral, é incompleta pois não define todos os métodos que ela utiliza.
+Os métodos ``indefinidos''\,---\,aqueles que outros métodos assumem existir, mas que não estão definidos\,---\,
+são chamados métodos \subind{método}{abstrato}s.
+\seeindex{classe abstrata}{classe, abstrata}
+\seeindex{método abstrato}{método, abstrato}
+
+\st não tem uma sintaxe específica para informar que um método ou uma classe são abstratos.
+Por convenção, o corpo de um método abstrato consiste da expressão \mbox{\ct{self subclassResponsibility}.}
+Isso é conhecido como um ``método marcado'' \footnote{marker method} e indica que as subclasses
+têm a responsabilidade de definir uma versão concreta do método.
+Métodos \ct{self subclassResponsibility} sempre devem ser sobreescritos e, portanto, nunca devem ser executados.
+Se você esquecer de sobreescrever um deles, e ele for executado, uma exceção serão lançada.
\cmindex{Object}{subclassResponsibility}
-A class is considered abstract if one of its methods is abstract.
-Nothing actually prevents you from creating an instance of an abstract class; everything will work until an abstract method is invoked.
+Uma classe é considerada abstrata se um de seus métodos for abstrato.
+Nada impede que você crie uma instância de uma classe abstrata; tudo funcionará até que métodos abstratos
+sejam invocados.
-\subsubsection{Example: the class \ct{Magnitude}.}
-\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}.
+\subsubsection{Examplo: a classe \ct{Magnitude}.}
+\clsind{Magnitude} é uma classe abstrata que nos ajuda a definir objetos que podem ser comparados com outros objetos.
+Subclasses de \ct{Magnitude} devem implementar os métodos \ct{<}, \ct{=} e \ct{hash}. Usando tais mensagens,
+\ct{Magnitude} define outros métodos como \ct{>}, \ct{>=}, \ct{<=}, \ct{max:}, \ct{min:} \ct{between:and:}
+e outros para comparar objetos. Estes mpetodos são herdados pelas subclasses. O método \mthind{Magnitude}{<}
+é abstrato e sua definição é ilustrada em \mthref{MagnitudeLessThan}.
\begin{method}[MagnitudeLessThan]{\ct{Magnitude>>><}}
Magnitude>>>< aMagnitude
- "Answer whether the receiver is less than the argument."
+ "Responde se o receptor e menor que o argumento."
^self subclassResponsibility
\end{method}
+%FIXME: comentário sem acento (... receptor é ...)
\noindent
-By contrast, the method \mthind{Magnitude}{>=} is concrete; it is defined in terms of \ct{<}:
+Em contraste, o método \mthind{Magnitude}{>=} é concreto; ele é definido em termos de \ct{<}:
\begin{method}[Magnitude>=]{\ct{Magnitude>>>>=}}
>= aMagnitude
- "Answer whether the receiver is greater than or equal to the argument."
+ "Responde se o receptor e maior ou igual ao argumento."
^(self < aMagnitude) not
\end{method}
-The same is true of the other comparison methods.
+%FIXME: comentário sem acento (... receptor é ...)
+O mesmo é verdadeiro para outros métodos de comparação.
-\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.
+A classe \clsind{Character} é uma subclasse de \ct{Magnitude}; ela sobreescrever o método
+\mthind{Object}{subclassResponsibility} por \ct{<} com sua própria versão de \ct{<}
+(veja \mthref{CharacterLessThan}). \ct{Character} também define os métodos
+\ct{=} e \ct{hash}; ela herda de \ct{Magnitude} os métodos \ct{>=}, \ct{<=}, \ct{~=} e outros.
\begin{method}[CharacterLessThan]{\ct{Character>>><}}
Character>>>< aCharacter
- "Answer true if the receiver's value < aCharacter's value."
+ "Responde true se o valor do receptor < o valor de aCharacter."
^self asciiValue < aCharacter asciiValue
\end{method}
+%FIXME: comentário sem acento (... receptor é ...)
%---------------------------------------------------------
\subsection{Traits}
-A \emphind{trait} is a collection of methods that can be included in the behaviour of a class without the need for inheritance.
-This makes it easy for classes to have a unique superclass, yet still share useful methods with otherwise unrelated classes.
+Um \emphind{trait} é uma coleção de métodos que podem ser incluídos no comportamento de uma classe
+sem precisar utilizar herança.
+Isso torna fácil o trabalho de compartilhar métodos úteis entre classes não relacionadas, mesmo
+que estas tenham apenas uma superclasse.
-To define a new trait, simply replace the subclass creation template by a message to the class \clsind{Trait}.
+Para definir um novo trait, simplesmente troque o modelo de criação de subclasse por uma mensagem
+para a classe \clsind{Trait}.
\needspace{5\baselineskip}
-\begin{classdef}[tauthor]{Defining a new trait}
+\begin{classdef}[tauthor]{Definindo um novo trait}
Trait named: #TAuthor
uses: { }
category: 'SBE-Quinto'
\end{classdef}
\noindent
-Here we define the trait \ct{TAuthor} in the category \scat{SBE-Quinto}.
-This trait does not \emph{use} any other existing traits.
-In general we can specify a \emph{trait composition expression} of other traits to use as part of the \ct{uses:} keyword argument.
-Here we simply provide an empty array.
+Aqui nós definimos o trait \ct{TAuthor} na categoria \scat{SBE-Quinto}.
+Este trait não \emph{usa} nenhum outro trait existente.
+Em 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:}.
+Aqui nós oferecemos apenas um array vazio.
-Traits may contain methods, but no instance variables.
-Suppose we would like to be able to add an \ct{author} method to various classes, independent of where they occur in the hierarchy.
-We might do this as follows:
+Traits podem conter métodos, mas não contém variáveis de instância.
+Suponha que nós queremos adicionar um método \ct{author} à várias classes, independente de
+onde elas se encontram na hierarquia.
+Nós poderiamos fazer o seguinte:
-\begin{method}[author]{An author method}
+\begin{method}[author]{Um método author}
TAuthor>>>author
- "Returns author initials"
+ "Retorna as iniciais do autor"
^ 'on' "oscar nierstrasz"
\end{method}
\noindent
-Now 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}.
-We simply modify the class creation template for \ct{SBEGame} to include a \ct{uses:} keyword argument that specifies that \ct{TAuthor} should be used.
+Agora nós podemos utilizar esta trait em uma classe que já tenha sua própria superclasse,
+por exemplo, a classe \ct{SBEGame} que definimos no \charef{firstApp}.
+Nós simplesmente modificamos o modelo de criação de classe pelo \ct{SBEGame} para incluir o
+argumento \ct{uses:} especificando que \ct{TAuthor} deve ser utilizado.
-\begin{classdef}[sbegamewithtrait]{Using a trait}
+\begin{classdef}[sbegamewithtrait]{Usando um trait}
BorderedMorph subclass: #SBEGame
uses: TAuthor
instanceVariableNames: 'cells'
@@ -554,21 +588,22 @@ BorderedMorph subclass: #SBEGame
category: 'SBE-Quinto'
\end{classdef}
-If we now instantiate \ct{SBEGame}, it will respond to the \ct{author} message as expected.
+Se nós instanciarmos um \ct{SBEGame}, o objeto responderá à mensagem \ct{author} como esperado.
\begin{code}{}
SBEGame new author --> 'on'
\end{code}
-Trait composition expressions may combine multiple traits using the \ct{+} operator.
-In 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.
-It is also possible to \emph{alias} methods (with \ct{@}), providing a new name for them.
+Expressões de composição de traits podem combinar múltiplas traits utilizando o operador \ct{+}.
+Em caso de conflito (isso é, se várias traits definem métodos com o mesmo nome), estes conflitos
+podem ser resolvidos explicitamente removendo estes métodos (com \ct{-}), ou redefinindo estes métodos
+na classe ou trait que você está criando.
+Também é possível \emph{apelidar} métodos (com \ct{@}), informando um novo nome para eles.
-Traits are used in the system kernel.
-One good example is the class \clsind{Behavior}.
+Os traits são utiliados no núcleo do sistema. Um bom exemplo é a classe \clsind{Behavior}
\needlines{8}
-\begin{classdef}[behaviorwithtraits]{\ct{Behavior} defined using traits}
+\begin{classdef}[behaviorwithtraits]{\ct{Behavior} definida utilizando traits}
Object subclass: #Behavior
uses: TPureBehavior @ {#basicAddTraitSelector:withMethod:->#addTraitSelector:withMethod:}
instanceVariableNames: 'superclass methodDict format'
@@ -577,8 +612,9 @@ Object subclass: #Behavior
category: 'Kernel-Classes'
\end{classdef}
\noindent
-Here we see that the method \ct{addTraitSelector:withMethod:} defined in the trait \ct{TPureBehavior} has been aliased to \ct{basicAddTraitSelector:withMethod:}.
-Support for traits is currently being added to the browsers.
+Aqui nós vemos que o método \ct{addTraitSelector:withMethod:} definido na trait \ct{TPureBehavior}
+foi apelidado para \ct{basicAddTraitSelector:withMethod:}.
+Suporte à traits está sendo adicionado aos browsers atualmente.
%=========================================================
\section{Everything happens by message sending} |