Patrones de Diseño

Descargar como docx, pdf o txt
Descargar como docx, pdf o txt
Está en la página 1de 10

Patrones de diseño:

Surgen a raíz de soluciones de problemas al momento de programar aplicaciones, páginas web,


etc. Existen 3 clasificaciones, están los creacionales, estructurales y de comportamiento

Tipo de patrones:

1. Creacionales
Solucionan problemas de creación de instancias, encapsulan y abstraen dicha información.

a. Object Pool: se utiliza para clases muy complejas y se basa en la clonación de la


misma instanciándola.
b. Abstract Factory: Permite trabajar con objetos de distintas familias de manera que
las familias no se mezclen entre sí, en ejemplo de ello es la utilización de
interfaces gráficas.
c. Builder: Abstrae el proceso de creación de un objeto y lo centraliza en un único
punto.
d. Factory Method: Centraliza las clases en una constructora la creación de objetos
de un subtipo de un tipo determinado
e. Prototype: Crea nuevos objetos clonándolos de una instancia ya existente.
f. Singleton: Garantiza la existencia de una única instancia para una clase y la
creación de un mecanismo de acceso global a dicha instancia.
g. Modelo Vista Controlador: Patrón de arquitectura de software que separa los
datos y la lógica de negocio de una aplicación de la interfaz de usuario y el
módulo encargado de gestionar los eventos y las comunicaciones.

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

Inyección de dependencias: Contenedor. (ej. del carro)


Especie de caja mágica el cual puede dar el objeto que solicitamos. Dentro del propio contenedor
contiene los objetos que necesitamos.

Muy útil para el uso de servicios Web, Api, etc.

Contenedor de servcios, de clases, etc. Util para objetos 3D.

Fly Weight – Peso Ligero – Peso Mosca.


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.

Observer
Permite que cuando un objeto cambie de estado se notifique y se actualice automáticamente a los
demás objetos dependientes de él.

Spring Versión actual 4.2 (2015) se utiliza con Java EE.

Api Java Reflection: Es la habilidad de utilizar y manipular las clases.

Inyección de dependencias

Beans
Inversion de dependencias

Deben estar desacoplados

Inversion de control (IoC)

Es un estilo de programación donde un agente externo controla el flujo de la aplicación

El objetivo es tener un código fácil de mantener

Spring Core Container:

Gestiona el ciclo de vida de los objetos (Beans)

 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

Listado de herramientas para testing


1. Selenium (Web Application Testing)
2. Appium (Mobile Testing)
3. JMeter (Load Testing)
4. Jenkins (Continuous Testing)
5. TestLink (Test Management)
6. Mantis (Bug-Tracking & Project Management)
7. Postman (API Testing)
8. Firebug / Firepath (Online Debugging)
9. GitHub (Project & Source Code Hosting)
10. Bugzilla (Defect Tracking & Collaboration)

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, …).

Conceptos Importantes de Programación Orientada a Objetos:

Existen varias definiciones de Programación Orientada a Objetos por parte de diferentes


autores, incluso usted mismo puede tener su propia definición una vez entendida esta técnica:
La Programación Orientada a objetos es un método de implementación en el que los
programas se organizan como colecciones cooperativas de objetos, cada uno de los cuales
representa una instancia de alguna clase, y cuyas clases son, todas ellas, miembros de una
jerarquía de clases unidas mediante relaciones de herencia [Grady Booch].

La Programación Orientada a objetos es un paradigma de programación que usa objetos y sus


interacciones para diseñar aplicaciones y programas de computadora. [Pendiente].

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.

Un objeto perteneciente a una determinada clase debe tener siempre un Estado, un


comportamiento y una Identidad. El estado es un dato del objeto, el comportamiento es la
acción que realiza y por su parte la identidad es un dato que hace diferente al objeto en
cuestión de otros objetos. Siguiendo el ejemplo del objeto Camioneta su estado es el color, su
comportamiento son las acciones que realiza, o sea los métodos transportar gente, acelerar y
frenar mientras que su identidad es el propio nombre del objeto.

La POO se basa también en algunos mecanismos que resultan bastante importantes en el


diseño del software, incluso algunos de éstos son considerados patrones de diseño:
Encapsulación: Es la habilidad de una parte del programa para ocultar sus datos al resto del
código del programa, impidiendo así los conflictos de acceso o incluso de seguridad de los
datos. También permite solucionar problemas de ambigüedad.

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.

Composición: Por composición se entiende la capacidad que presenta la POO de ensamblar un


nuevo tipo (clase) cuyos elementos o piezas son otras clases. (Pendiente).

Concurrencia: Cuando un programa puede atender varios procesos al “mismo tiempo”,


básicamente se refiere al manejo de Hilos.

Persistencia: Cuando un objeto puede transcender a través del tiempo.

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

Shared with non-OOP predecessor languages[edit]


 Variables that can store information formatted in a small number of built-in data
types like integers and alphanumeric characters. This may include data
structures like strings, lists, and hash tables that are either built-in or result from combining
variables using memory pointers
 Procedures – also known as functions, methods, routines, or subroutines – that take input,
generate output, and manipulate data. Modern languages include structured
programming constructs like loops and conditionals.
Modular programming support provides the ability to group procedures into files and modules
for organizational purposes. Modules are namespaced so identifiers in one module will not be
accidentally confused with a procedure or variable sharing the same name in another file or
module.

Objects and classes[edit]


Languages that support object-oriented programming typically use inheritance for code reuse
and extensibility in the form of either classes or prototypes. Those that use classes support two
main concepts:

 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.

Junade Ali, Mastering PHP Design Patterns[8]


Each object is said to be an instance of a particular class (for example, an object with its name
field set to "Mary" might be an instance of class Employee). Procedures in object-oriented
programming are known as methods; variables are also known as fields, members, attributes,
or properties. This leads to the following terms:

 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.

Dynamic dispatch/message passing[edit]


It is the responsibility of the object, not any external code, to select the procedural code to
execute in response to a method call, typically by looking up the method at run time in a table
associated with the object. This feature is known as dynamic dispatch, and distinguishes an
object from an abstract data type (or module), which has a fixed (static) implementation of the
operations for all instances. If the call variability relies on more than the single type of the
object on which it is called (i.e. at least one other parameter object is involved in the method
choice), one speaks of multiple dispatch.
A method call is also known as message passing. It is conceptualized as a message (the name
of the method and its input parameters) being passed to the object for dispatch.

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.

También podría gustarte