What design patterns do you know? Tell about Proxy, Factory, Strategy.
sobes.tech AI
Answer from AI
Here is a brief description of three design patterns:
-
Proxy — an object that controls access to another object, adding additional logic (e.g., lazy initialization, caching, access control).
Example: a proxy for lazy loading a resource.
-
Factory — a pattern for creating objects without specifying the exact class of the object to be created. It allows creating objects through a common interface.
Example: a factory that creates different types of documents based on the type.
-
Strategy — a pattern that allows selecting an algorithm at runtime, encapsulating different algorithms into separate classes.
Example: different sorting algorithms chosen depending on the data.
Example of Proxy in Java:
interface Image {
void display();
}
class RealImage implements Image {
private String filename;
RealImage(String filename) { this.filename = filename; loadFromDisk(); }
void loadFromDisk() { System.out.println("Loading " + filename); }
public void display() { System.out.println("Displaying " + filename); }
}
class ProxyImage implements Image {
private RealImage realImage;
private String filename;
ProxyImage(String filename) { this.filename = filename; }
public void display() {
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}
This proxy defers the loading of the image until the display() method is called.