美文网首页
枚举实现单例和策略模式

枚举实现单例和策略模式

作者: 要不再等等 | 来源:发表于2020-03-20 11:51 被阅读0次

单例模式

public enum PizzaDeliverySystemConfiguration {
    INSTANCE;
    PizzaDeliverySystemConfiguration() {
        // Initialization configuration which involves
        // overriding defaults like delivery strategy
    }
 
    private PizzaDeliveryStrategy deliveryStrategy = PizzaDeliveryStrategy.NORMAL;
 
    public static PizzaDeliverySystemConfiguration getInstance() {
        return INSTANCE;
    }
 
    public PizzaDeliveryStrategy getDeliveryStrategy() {
        return deliveryStrategy;
    }
}

使用方法:

PizzaDeliveryStrategy deliveryStrategy = PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy();

策略模式

public enum PizzaDeliveryStrategy {
    EXPRESS {
        @Override
        public void deliver(Pizza pz) {
            System.out.println("Pizza will be delivered in express mode");
        }
    },
    NORMAL {
        @Override
        public void deliver(Pizza pz) {
            System.out.println("Pizza will be delivered in normal mode");
        }
    };
 
    public abstract void deliver(Pizza pz);
}

如何使用

PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy()
          .deliver(new Pizza());

相关文章

网友评论

      本文标题:枚举实现单例和策略模式

      本文链接:https://www.haomeiwen.com/subject/vmtjyhtx.html