Abstract Factory with Bridge

You can use Abstract Factory along with Bridge. This pairing is useful when some abstractions defined by Bridge can only work with specific implementations. In this case, Abstract Factory can encapsulate these relations and hide the complexity from the client code.
mail@pastecode.io avatar
unknown
java
7 months ago
1.9 kB
22
Indexable
Never
// Step 1: Abstraction Hierarchy
interface Shape {
    void draw();
}

class Circle implements Shape {
    private Color color;

    public Circle(Color color) {
        this.color = color;
    }

    @Override
    public void draw() {
        System.out.print("Draw a Circle ");
        color.applyColor();
    }
}

class Rectangle implements Shape {
    private Color color;

    public Rectangle(Color color) {
        this.color = color;
    }

    @Override
    public void draw() {
        System.out.print("Draw a Rectangle ");
        color.applyColor();
    }
}

// Step 2: Implementation Hierarchy
interface Color {
    void applyColor();
}

class RedColor implements Color {
    @Override
    public void applyColor() {
        System.out.println("with Red Color.");
    }
}

class BlueColor implements Color {
    @Override
    public void applyColor() {
        System.out.println("with Blue Color.");
    }
}

// Step 3: Abstract Factory
interface ShapeFactory {
    Shape createShape();
}

class RedShapeFactory implements ShapeFactory {
    @Override
    public Shape createShape() {
        return new Circle(new RedColor());
    }
}

class BlueShapeFactory implements ShapeFactory {
    @Override
    public Shape createShape() {
        return new Rectangle(new BlueColor());
    }
}

// Step 4: Client Code
public class Main {
    public static void main(String[] args) {
        // Create a red shape factory
        ShapeFactory redFactory = new RedShapeFactory();

        // Create a red circle and draw it
        Shape redCircle = redFactory.createShape();
        redCircle.draw();

        // Create a blue shape factory
        ShapeFactory blueFactory = new BlueShapeFactory();

        // Create a blue rectangle and draw it
        Shape blueRectangle = blueFactory.createShape();
        blueRectangle.draw();
    }
}