Junior — Middle
What patterns from the Gemma catalog do you apply in your projects to solve typical tasks?
sobes.tech AI
Answer from AI
In my C# projects, I often apply the following patterns from the Gamma catalog to solve typical tasks:
- Singleton — to ensure a single instance of a class, for example, for a configuration manager or logger.
- Factory Method — to create objects without tight coupling to specific classes, which facilitates extension and testing.
- Observer — to implement an event-driven model where objects subscribe to changes in the state of another object.
- Decorator — to dynamically add functionality to objects without changing their code.
- Strategy — to select an algorithm for behavior at runtime, such as different sorting or validation methods.
Example of using the Strategy pattern:
public interface ICompressionStrategy
{
void Compress(string fileName);
}
public class ZipCompression : ICompressionStrategy
{
public void Compress(string fileName) {
Console.WriteLine($"Compressing {fileName} using ZIP");
}
}
public class RarCompression : ICompressionStrategy
{
public void Compress(string fileName) {
Console.WriteLine($"Compressing {fileName} using RAR");
}
}
public class CompressionContext
{
private ICompressionStrategy _strategy;
public CompressionContext(ICompressionStrategy strategy) {
_strategy = strategy;
}
public void SetStrategy(ICompressionStrategy strategy) {
_strategy = strategy;
}
public void CreateArchive(string fileName) {
_strategy.Compress(fileName);
}
}
This approach allows for flexible changes in program behavior without modifying client code.