Patrones de Diseño
Patrones de Diseño
Patrones de Diseño
Tipo de patrones:
1. Creacionales
Solucionan problemas de creación de instancias, encapsulan y abstraen dicha información.
2. Estructurales
Son los que solucionan problemas de composición (agregación) de clases y objetos.
a. Adapter o Wrapper; adapta la interfaz para que otra clase pueda utilizarla.
b. Bridge: Desacopla una abstracción de su implementación.
c. Composite: Permite tratar objetos compuestos como si de una simple se tratase.
d. Decorator: Añade funcionalidad a una clase dinámicamente.
e. Facade: Provee de una interfaz unificada simple para acceder a una interfaz o
grupo de interfaces de un subsitema.
f. Fly Weight: Se utiliza para la creación de objetos costosos a nivel de capacidad de
almacenamiento, la solución es intuitiva y simple: que los objetos creados apunten
a una misma referencia de memoria, al mismo recurso el número de veces que
sea necesario.
g. Proxy:
h. Module
3. De Comportamiento
Se definen como patrones de diseño de software que ofrecen soluciones respecto a la interacción
y responsabilidades entre clases y objetos, así como los algoritmos que encapsulan.
a. Chain of Responsability
b. Command
c. Interpreter
d. Iterator.
e. Meidator
f. Memento
g. Observer
h. State
i. Strategy
j. Template Method
k. Visitor
Observer
Permite que cuando un objeto cambie de estado se notifique y se actualice automáticamente a los
demás objetos dependientes de él.
Inyección de dependencias
Beans
Inversion de dependencias
Crearlos
Enlazarlos
Configurarlos
Destruirlos
Flexibilidad, integración con otras tecnologías
Código ordenado.
Uso de anotaciones
Inyección de dependencias.
Estándares de programación
Polimorfismo: El polimorfismo es una relajación del sistema de tipos, de tal manera que una
referencia a una clase (atributo, parámetro o declaración local o elemento de un vector)
acepta direcciones de objetos de dicha clase y de sus clases derivadas (hijas, nietas, …).
La Programación Orientada a Objetos es una técnica de Programación que toma las mejores
ideas de la programación estructurada y las combina con nuevos conceptos de organización,
define los programas en términos de clases y objetos los cuales se comunican entre sí por
medio de mensajes para crear aplicaciones y programas de computadora. [R.R].
Una clase es una descripción generalizada (por ejemplo, una plantilla, un patrón o un
prototipo) que describe una colección de objetos similares [UML Manual de referencia]. Una
clase se compone de métodos y atributos, un método se entiende como el comportamiento
que se define en una clase, los atributos son las características de las clases. Un ejemplo de
clase es la clase Automóvil, en donde se sabe que los atributos de un automóvil son, por citar
algunos, el color, la marca, el modelo y el número de placas, por otro lado los métodos de un
Automóvil (o sea lo que hace) son transportar gente, acelerar y frenar.
Por otra parte un objeto es una entidad discreta, con límites bien definidos y con identidad,
que encapsula el estado y el comportamiento, por ejemplo, de la clase Automóvil puede
derivarse un objeto Camioneta que tiene un color, una marca, un modelo y un número de
placas y además transporta gente, acelera y frena.
Herencia: es una relación entre clases en la que una clase comparte la estructura y/o
comportamiento definido en una (herencia simple) o más clases (herencia múltiple) [Grady
Booch]. (Véase el artículo dedicado a la herencia en éste sitio).
Polimorfismo: Es tan natural como cuando un objeto se puede comportar de muchas formas o
un método puede tener diferentes comportamientos recibiendo diferentes tipos de
parámetros.
Features[edit]
Object-oriented programming uses objects, but not all of the associated techniques and
structures are supported directly in languages that claim to support OOP. The features listed
below are, however, common among languages considered strongly class- and object-oriented
(or multi-paradigm with OOP support), with notable exceptions mentioned.[3][4][5][6]
See also: Comparison of programming languages (object-oriented programming) and List of
object-oriented programming terms
Classes – the definitions for the data format and available procedures for a given type or
class of object; may also contain data and procedures (known as class methods)
themselves, i.e. classes contain the data members and member functions
Objects – instances of classes
Objects sometimes correspond to things found in the real world. For example, a graphics
program may have objects such as "circle", "square", "menu". An online shopping system
might have objects such as "shopping cart", "customer", and "product".[7] Sometimes objects
represent more abstract entities, like an object that represents an open file, or an object that
provides the service of translating measurements from U.S. customary to metric.
Object-oriented programming is more than just classes and objects; it's a whole programming paradigm based
around objects (data structures) that contain data fields and methods. It is essential to understand this; using
classes to organize a bunch of unrelated methods together is not object orientation.
Class variables – belong to the class as a whole; there is only one copy of each one
Instance variables or attributes – data that belongs to individual objects; every object has
its own copy of each one
Member variables – refers to both the class and instance variables that are defined by a
particular class
Class methods – belong to the class as a whole and have access only to class variables
and inputs from the procedure call
Instance methods – belong to individual objects, and have access to instance variables for
the specific object they are called on, inputs, and class variables
Objects are accessed somewhat like variables with complex internal structure, and in many
languages are effectively pointers, serving as actual references to a single instance of said
object in memory within a heap or stack. They provide a layer of abstraction which can be used
to separate internal from external code. External code can use an object by calling a specific
instance method with a certain set of input parameters, read an instance variable, or write to an
instance variable. Objects are created by calling a special type of method in the class known
as a constructor. A program may create many instances of the same class as it runs, which
operate independently. This is an easy way for the same procedures to be used on different
sets of data.
Object-oriented programming that uses classes is sometimes called class-based programming,
while prototype-based programming does not typically use classes. As a result, a significantly
different yet analogous terminology is used to define the concepts of object and instance.
In some languages classes and objects can be composed using other concepts
like traits and mixins.
Class-based vs prototype-based[edit]
In class-based languages the classes are defined beforehand and the objects are instantiated
based on the classes. If two objects apple and orange are instantiated from the class Fruit,
they are inherently fruits and it is guaranteed that you may handle them in the same way; e.g. a
programmer can expect the existence of the same attributes such as color or sugar
content or is ripe.
In prototype-based languages the objects are the primary entities. No classes even exist.
The prototype of an object is just another object to which the object is linked. Every object has
one prototype link (and only one). New objects can be created based on already existing
objects chosen as their prototype. You may call two different objects apple and orange a fruit, if
the object fruit exists, and both apple and orange have fruit as their prototype. The idea of
the fruit class doesn't exist explicitly, but as the equivalence class of the objects sharing the
same prototype. The attributes and methods of the prototype are delegated to all the objects of
the equivalence class defined by this prototype. The attributes and methods owned individually
by the object may not be shared by other objects of the same equivalence class; e.g. the
attributes sugar content may be unexpectedly not present in apple. Only single inheritance can
be implemented through the prototype.
Encapsulation[edit]
Encapsulation is an object-oriented programming concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and
misuse. Data encapsulation led to the important OOP concept of data hiding.
If a class does not allow calling code to access internal object data and permits access through
methods only, this is a strong form of abstraction or information hiding known as encapsulation.
Some languages (Java, for example) let classes enforce access restrictions explicitly, for
example denoting internal data with the private keyword and designating methods intended
for use by code outside the class with the public keyword. Methods may also be designed
public, private, or intermediate levels such as protected (which allows access from the same
class and its subclasses, but not objects of a different class). In other languages (like Python)
this is enforced only by convention (for example, private methods may have names that
start with an underscore). Encapsulation prevents external code from being concerned with the
internal workings of an object. This facilitates code refactoring, for example allowing the author
of the class to change how objects of that class represent their data internally without changing
any external code (as long as "public" method calls work the same way). It also encourages
programmers to put all the code that is concerned with a certain set of data in the same class,
which organizes it for easy comprehension by other programmers. Encapsulation is a
technique that encourages decoupling.
Composition, inheritance, and delegation[edit]
Objects can contain other objects in their instance variables; this is known as object
composition. For example, an object in the Employee class might contain (either directly or
through a pointer) an object in the Address class, in addition to its own instance variables like
"first_name" and "position". Object composition is used to represent "has-a" relationships:
every employee has an address, so every Employee object has access to a place to store an
Address object (either directly embedded within itself, or at a separate location addressed via a
pointer).
Languages that support classes almost always support inheritance. This allows classes to be
arranged in a hierarchy that represents "is-a-type-of" relationships. For example, class
Employee might inherit from class Person. All the data and methods available to the parent
class also appear in the child class with the same names. For example, class Person might
define variables "first_name" and "last_name" with method "make_full_name()". These will also
be available in class Employee, which might add the variables "position" and "salary". This
technique allows easy re-use of the same procedures and data definitions, in addition to
potentially mirroring real-world relationships in an intuitive way. Rather than utilizing database
tables and programming subroutines, the developer utilizes objects the user may be more
familiar with: objects from their application domain.[9]
Subclasses can override the methods defined by superclasses. Multiple inheritance is allowed
in some languages, though this can make resolving overrides complicated. Some languages
have special support for mixins, though in any language with multiple inheritance, a mixin is
simply a class that does not represent an is-a-type-of relationship. Mixins are typically used to
add the same methods to multiple classes. For example, class UnicodeConversionMixin might
provide a method unicode_to_ascii() when included in class FileReader and class
WebPageScraper, which don't share a common parent.
Abstract classes cannot be instantiated into objects; they exist only for the purpose of
inheritance into other "concrete" classes which can be instantiated. In Java,
the final keyword can be used to prevent a class from being subclassed.
The doctrine of composition over inheritance advocates implementing has-a relationships using
composition instead of inheritance. For example, instead of inheriting from class Person, class
Employee could give each Employee object an internal Person object, which it then has the
opportunity to hide from external code even if class Person has many public attributes or
methods. Some languages, like Go do not support inheritance at all.
The "open/closed principle" advocates that classes and functions "should be open for
extension, but closed for modification".
Delegation is another language feature that can be used as an alternative to inheritance.
Polymorphism[edit]
Subtyping, a form of polymorphism, is when calling code can be agnostic as to whether an
object belongs to a parent class or one of its descendants. For example, a function might call
"make_full_name()" on an object, which will work whether the object is of class Person or class
Employee. This is another type of abstraction which simplifies code external to the class
hierarchy and enables strong separation of concerns.
Open recursion[edit]
In languages that support open recursion, object methods can call other methods on the same
object (including themselves), typically using a special variable or keyword
called this or self . This variable is late-bound; it allows a method defined in one class to
invoke another method that is defined later, in some subclass thereof.