What are strategies in java with examples

Savannah 17 Published: 11/19/2024

What are strategies in java with examples

I'm happy to help you with that!

Java is an object-oriented programming language known for its platform independence and versatility. Here, we'll dive into some of the most effective strategies used in Java, along with examples:

Single Responsibility Principle (SRP): Each class should have a single responsibility and not be overly complex.

Example:

// Bad implementation

public class Employee {

public void updateName(String name) {

this.name = name;

}

public void calculateSalary() {

// calculation logic

}

}

// Good implementation

public interface UpdateName {

void setName(String name);

}

public interface CalculateSalary {

int calculate();

}

public class Employee implements UpdateName, CalculateSalary {

private String name;

@Override

public void setName(String name) {

this.name = name;

}

@Override

public int calculate() {

// calculation logic

}

}

Don't Repeat Yourself (DRY): Avoid duplicating code by extracting reusable blocks into separate methods or classes.

Example:

// Duplicate code

public class BankAccount {

public void debit(int amount) {

System.out.println("Debiting " + amount);

}

public void credit(int amount) {

System.out.println("Crediting " + amount);

}

}

// Improved implementation using DRY principle

public abstract class Transaction {

public abstract void processTransaction(int amount);

}

public class Debit extends Transaction {

@Override

public void processTransaction(int amount) {

System.out.println("Debiting " + amount);

}

}

public class Credit extends Transaction {

@Override

public void processTransaction(int amount) {

System.out.println("Crediting " + amount);

}

}

Encapsulation: Hide internal implementation details and expose only necessary information through a controlled interface.

Example:

// Poor encapsulation

public class Person {

private String name;

public void setName(String name) {

this.name = name;

}

public String getName() {

return name;

}

}

// Improved encapsulation using access modifiers

public class Person {

private final String name; // Immutable

public Person(String name) {

this.name = name;

}

public String getName() {

return name;

}

}

Composition: Combine objects to form a new, more complex object that exhibits specific behaviors.

Example:

// Simple implementation

public class Car {

private Engine engine;

public void startEngine() {

engine.start();

}

}

public class Truck extends Car {

// ...

}

// Composition example

public interface Engine {

void start();

}

public class GasolineEngine implements Engine {

@Override

public void start() {

System.out.println("Gasoline engine started");

}

}

public class ElectricEngine implements Engine {

@Override

public void start() {

System.out.println("Electric engine started");

}

}

public class Car {

private final Engine engine;

public Car(Engine engine) {

this.engine = engine;

}

public void startEngine() {

engine.start();

}

}

Factory Method: Provide a way to create objects without specifying the exact class type.

Example:

// Simple implementation

public abstract class Vehicle {

public abstract void drive();

}

public class Car extends Vehicle {

@Override

public void drive() {

System.out.println("Driving a car");

}

}

public class Truck extends Vehicle {

@Override

public void drive() {

System.out.println("Driving a truck");

}

}

// Factory method example

public interface VehicleFactory {

Vehicle createVehicle();

}

public class CarFactory implements VehicleFactory {

@Override

public Vehicle createVehicle() {

return new Car();

}

}

public class TruckFactory implements VehicleFactory {

@Override

public Vehicle createVehicle() {

return new Truck();

}

}

These strategies can help you write more maintainable, flexible, and scalable code in Java. Remember to apply these principles judiciously, as over-engineering can be detrimental to the overall system performance.

What is the difference between factory and strategy in java

I'm happy to help you with that!

In Java, Factory and Strategy are two design patterns that aim to solve specific problems in object-oriented programming. While they share some similarities, they serve distinct purposes.

Factory Pattern:

The Factory pattern is used to create objects without exposing the creation logic to the client code. It provides a way to decouple object creation from the rest of the application, making it easier to add or remove concrete classes that implement an abstract class.

In a factory, you define an interface or abstract class that specifies the common attributes and behaviors for all objects created by the factory. Then, you create concrete classes that extend this abstract class and provide their own implementations. When a client needs an object of a specific type, it asks the factory for an instance of that type.

For example, imagine a game with different types of enemies (e.g., zombies, aliens, robots). You can create a EnemyFactory that returns instances of these enemy classes based on some criteria (e.g., difficulty level). The client code doesn't need to know about the specific implementations; it only needs to ask the factory for an enemy.

Strategy Pattern:

The Strategy pattern is used to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. This allows you to change the algorithm or strategy used by a class without affecting the rest of the application.

In a strategy, you define an interface that specifies the common behavior for all algorithms. Then, you create concrete classes that implement this interface and provide their own implementations. When a client needs to perform some operation using a specific strategy, it asks the strategy object for the required algorithm.

For instance, imagine a game with different AI strategies (e.g., aggressive, defensive, random). You can create a GameAI class that uses an AIStrategy interface. Concrete classes like AggressiveAI, DefensiveAI, and RandomAI implement this interface, providing their own logic for decision-making.

Key differences:

Creation vs. Selection: The Factory pattern focuses on object creation, while the Strategy pattern is concerned with algorithm selection or substitution. Object lifetime: In a factory, objects are typically short-lived and created only when needed. In a strategy, objects can exist throughout the application's lifetime, as they provide long-term behavior. Encapsulation: Factories tend to encapsulate the creation logic, while strategies encapsulate the algorithm or logic itself.

In summary, the Factory pattern helps create objects without exposing their creation logic, whereas the Strategy pattern enables you to define and swap algorithms or strategies used by a class. While both patterns aim to improve flexibility and decoupling in your code, they serve distinct purposes and are used in different scenarios.