桥接模式【结构模式】

桥接模式

Decouple an abstraction from its implementation so that the two can very independently.
将抽象和实现解耦,这样两者就可以独立发展。
public class GitBridge {

    @Test
    public void all() {
        /**
         * Weapon 和 Enchantment 可以任意组合,独立发展。
         */
        final FlyingEnchantment flyingEnchantment = FlyingEnchantment.builder().build();
        final SoulEatingEnchantment soulEatingEnchantment = SoulEatingEnchantment.builder().build();

        final Sword sword = Sword.builder().enchantment(flyingEnchantment).build();
        sword.wield();
        sword.swing();
        sword.unwield();

        final Hammer hammer = Hammer.builder().enchantment(soulEatingEnchantment).build();
        hammer.wield();
        hammer.swing();
        hammer.unwield();
    }
}

interface Weapon {
    void wield();

    void swing();

    void unwield();

    Enchantment getEnchantment();
}

interface Enchantment {
    void onActivate();

    void apply();

    void onDeactivate();
}

@Builder
@Slf4j
class FlyingEnchantment implements Enchantment {

    @Override
    public void onActivate() {
        log.info("The item begins to glow faintly.");
    }

    @Override
    public void apply() {
        log.info("The item flies and strikes the enemies finally returning to owner's hand.");
    }

    @Override
    public void onDeactivate() {
        log.info("The item's glow fades.");
    }
}

@Slf4j
@Builder
class SoulEatingEnchantment implements Enchantment {

    @Override
    public void onActivate() {
        log.info("The item spreads bloodlust.");
    }

    @Override
    public void apply() {
        log.info("The item eats the soul of enemies.");
    }

    @Override
    public void onDeactivate() {
        log.info("Bloodlust slowly disappears.");
    }
}

@Slf4j
@Builder
class Sword implements Weapon {
    private final Enchantment enchantment;

    @Override
    public void wield() {
        log.info("The sword is wielded.");
        enchantment.onActivate();
    }

    @Override
    public void swing() {
        log.info("The sword is swinged.");
        enchantment.apply();
    }

    @Override
    public void unwield() {
        log.info("The sword is unwielded.");
        enchantment.onDeactivate();
    }

    @Override
    public Enchantment getEnchantment() {
        return enchantment;
    }
}

@Slf4j
@Builder
class Hammer implements Weapon {
    private final Enchantment enchantment;

    @Override
    public void wield() {
        log.info("The hammer is wielded.");
        enchantment.onActivate();
    }

    @Override
    public void swing() {
        log.info("The hammer is swinged.");
        enchantment.apply();
    }

    @Override
    public void unwield() {
        log.info("The hammer is unwielded.");
        enchantment.onDeactivate();
    }

    @Override
    public Enchantment getEnchantment() {
        return enchantment;
    }
}

posted on 2018-12-23 14:49  竺旭东  阅读(98)  评论(0编辑  收藏  举报

导航