Java 接口应用-策略模式
/* * 策略模式(strategy pattern),定义了一系列算法,将每一种算法封装起来可以相互替换使用 */ public class TestCeLue { public static void main(String[] args) { UserService us = new UserService(); us.setISave(new NetSave()); us.save(); } } //把可变的行为抽象出来 interface ISave{ public abstract void save(); } class FileSave implements ISave{ public void save() { System.out.println("实现文件存储"); } } class NetSave implements ISave{ public void save() { System.out.println("实现网络存储"); } } abstract class BaseService{ private ISave iSave; public void setISave(ISave iSave) { this.iSave = iSave; } public void save() { System.out.println("检查数据合法性"); iSave.save(); System.out.println("数据保存成功"); } } class UserService extends BaseService{ }
本文来自博客园,作者:藤原豆腐渣渣,转载请注明原文链接:https://www.cnblogs.com/javafufeng/p/16276777.html