DESIGN PATTERNS
Sono indipendenti dal linguaggio, ma scriverli due volte sicuro non mi fa male
https://refactoring.guru/design-patterns/
IN PYTHON¶
https://www.linkedin.com/learning/python-design-patterns/types-of-design-patterns?u=42751868
- CREATIONAL:
Create objects in a flexible way. Polymorphism. - STRUCTURAL:
Relationship between elements - Inheritance - BEHAVIORAL:
Object interactions. Methods and signatures.
CREATIONAL {#creational}¶
-
Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
https://refactoring.guru/design-patterns/factory-method/python/example -
Abstract Factory is a creational design pattern that lets you produce families of related objects without specifying their concrete classes.
-
Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.
- Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
- Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.
The pattern requires special treatment in a multithreaded environment so that multiple threads won’t create a singleton object several times.
-
Builder is a creational design pattern that lets you construct complex objects step by step. The pattern allows you to produce different types and representations of an object using the same construction code.
-
Prototype is a creational design pattern that lets you copy existing objects without making your code dependent on their classes.
STRUCTURAL {#structural}¶
-
Decorator is a structural design pattern that lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the behaviors.
-
Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.
Use the pattern when you want to reuse several existing subclasses that lack some common functionality that can’t be added to the superclass. -
Composite is a structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual objects.
Using the Composite pattern makes sense only when the core model of your app can be represented as a tree. -
Bridge is a structural design pattern that lets you split a large class or a set of closely related classes into two separate hierarchies—abstraction and implementation—which can be developed independently of each other.
Use the pattern when you need to extend a class in several orthogonal (independent) dimensions.
Use the Bridge if you need to be able to switch implementations at runtime.
BEHAVIORAL {#behavioral}¶
-
Observer is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.
Use the Observer pattern when changes to the state of one object may require changing other objects, and the actual set of objects is unknown beforehand or changes dynamically.
X Subscribers are notified in random order.
→ singleton -
Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate.
Use the Visitor when you need to perform an operation on all elements of a complex object structure (for example, an object tree).
Use the pattern when a behavior makes sense only in some classes of a class hierarchy, but not in others.
→ can also provide functionalities to Composite objects -
Iterator is a behavioral design pattern that lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.).
-
Strategy is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
-
Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.
¶
IN JAVA¶
https://dzone.com/refcardz/design-patterns?chapter=17
¶
Creational Patterns¶
Lets create objects without specifying their concrete class.
Object level.
Ensure a class has only one instance and provide a global point of access to it.
Constructor must be private.
Usi comuni: thread pool, registry, logging.
Singleton is infamous in object oriented systems. A lot of the time the Singleton is used as a shortcut, so that the designer doesn't need to think properly about object visibility. If you're hacking in a Singleton so that there is global access to a resource, maybe it's not the right thing to do. It might be better to work out how to pass the reference to that resource around properly.
Structural Patterns¶
It’s a bridge between two different interfaces.
Object level.
Let decouple an abstraction from its implementation, letting them be modified independently.
Aggiunge dinamicamente a runtime attributi ad un oggetto.
The concept of a decorator is that it adds additional attributes to an object dynamically.
Open/Closed Principle: classes should be open for extension, but closed for modification.
Too much subclassing is definitely a bad thing. As you add more behaviours to a base class, you will soon find yourself dealing with maintenance nightmare, as a new class is created for each possible combination.
https://www.programmerinterview.com/index.php/design-pattern-questions/decorator-pattern-versus-inheritance/
Un sistema (@Stateless o @Stateful) che raggruppa più servizi (@EJB)
https://dzone.com/articles/design-patterns-uncovered-1
https://www.oracle.com/technetwork/java/sessionfacade-141285.html
All EJB are transactional and thread safe by default.
Behavioral Patterns¶
- Learn The Chain of Responsibility Pattern
- Learn The Command Pattern
- Learn The Interpreter Pattern
- Learn The Iterator Pattern
- Learn The Mediator Pattern
- Learn The Memento Pattern
- Learn The Observer Pattern
Java as built in Observer pattern: a Subject object when changing state send a message without knowing if it will be read, on the other side there could be other objects, the Observers, that get notified about the change, in a sync or async way.
E’ possibile assegnare una @Priority e un tipo all’evento per differenziare i metodi in ascolto.
Async injected events possono essere associati ad un numero minimo di threads associati
@Injectprivate Event\<Customer> customerMessage;public void newCustomer(Customer c){ customerMessage.fire(c);}//---public void createCustomer(@Observes Customer c){ // ..} |
---|
- Learn The State Pattern
- Learn The Strategy Pattern
- Learn The Template Method Pattern
- Learn The Visitor Pattern
Circuit Breaker
https://martinfowler.com/bliki/CircuitBreaker.html
THE FILTER PATTERN
Pre processing and post-processing of data
Mostly used in web to intercept servlet request and response to: log, compress
public class authFilter implements Filter{ @Override Public void doFilter(ServletRequest sreq, ServletResponse sresp, Filter chain){ } } |
---|
INTERCEPTOR PATTERN
AOP = Aspect Oriented Programming. Not business concerns: security..
HandlerInterceptor is basically similar to a Servlet Filter, but in contrast to the latter it just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing. Filters are more powerful, for example they allow for exchanging the request and response objects that are handed down the chain. Note that a filter gets configured in web.xml, a HandlerInterceptor in the application context.
As a basic guideline, fine-grained handler-related preprocessing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.
MVC
Persistence --- business (M) --- presentation (VC) --- client
Model: Application data with logic. @Model class with getters and setter on attributes to display.
Controller: links view and model.
View: filter of the model data. JSF
ARCHITECTURES
DOMAIN ARCHITECTURE
Hexagonal: adapter as external interfaces (messaging, db..). Inside use cases and domain model. Can be tested without touching presentation layer.
Onion, Clean.
Presentation can change easily thanks to decoupling.
Hard to separate domain info from a standard application layer.
JAVA code
- parenthesis parser - Stack
- creazione di oggetti da clase Factory, di tipi diversi a seconda della stringa passata al metodo pubblico
- array list:
List\<List\<String>> dict = new ArrayList\<>();
List\<List\<String>> list = new ArrayList\<List\<String>>();
JAVA theory
- encapsulation vs
DB
THREAD
is a live instance of a program, managed by the Operative system scheduler. generally multiple threads compose one process
threads share memory while processes don't share address spaces
Systems with a single processor generally implement multithreading by time slicing: the central processing unit (CPU) switches between different software threads. This context switching generally happens very often and rapidly enough that users perceive the threads or tasks as running in parallel. On a multiprocessor or multi-core system, multiple threads can execute in parallel, with every processor or core executing a separate thread simultaneously;
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
ITERATOR
move on the elements of a Collection. It let know if there are more, and to modify them, even even delete
A collection represents a group of objects, known as its elements. Some collections allow duplicate elements (Queue) and others do not (Set).
ABSTRACT class
cannot be instantiated
An abstract class is used by creating an inheriting subclass that can be instantiated.
Advantages:
Define methods which can be used by the inheriting subclass.
Define abstract methods which the inheriting subclass must implement.
Provide a common interface which allows the subclass to be interchanged with all other subclasses.
STATIC
the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type, so it is shared between instances
It doesn’t matter how many times we initialize a class
static methods are also widely used to create utility or helper classes so that they can be obtained without creating a new object of these classes.
If static variables require additional, multi-statement logic while initialization, then a static block can be used.
The most widely used approach to create SINGLETON objects is through static nested class is it doesn’t require any synchronization and is easy to implement
FINAL
if a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.
A final class cannot be subclassed (String)
A final method cannot be overridden or hidden by subclasses
A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration.
Unlike the value of a constant, the value of a final variable is not necessarily known at compile time.