通过自己写例子理解工厂模式
测试工厂类,了解AOP,IOC机制.
通过UserDao的接口来调用不同的方法来存储实例.
首先有UserDao接口.有各种实现类.
其次有一个管理类UserMangaer,来实现接口中各种方法的使用.
再次有一个Test类来测试,通过自己创建UserMangaer来调用UserDao接口中的方法
用到了多态,单例模式,跟工厂模式.
Spring就是把各种接口的实现放入到配置里,然后根据情况来调用.
package zhc.love.dj.Dao; public interface UserDao { public void save(String name ,String password); }
package zhc.love.dj.Dao; public class UserDaoFactory { private static UserDaoFactory instance = new UserDaoFactory(); private UserDaoFactory(){ } public static UserDaoFactory getInstance(){ return instance ; } public UserDao CreatUserDao(){ return new UserDaoMysqlImp(); } }
package zhc.love.dj.Dao; public class UserDaoMysqlImp implements UserDao { public void save(String name, String password) { System.out.println("----------MySql.save()------------"); } }
//通过这个类来调用Userdao接口.这个类为工厂类
package zhc.love.dj.Maneger; import zhc.love.dj.Dao.UserDao; import zhc.love.dj.Dao.UserDaoFactory; public class UserMangaer { UserDao userdao ; //单例模式的三点要素 ,线程不安全的. //1:私有的静态的实例. private static UserMangaer instance = new UserMangaer(); //2.私有构造方法 private UserMangaer(){ userdao = UserDaoFactory.getInstance().CreatUserDao() ; } //共有的静态方法. public static UserMangaer getInstance(){ return instance ; } public void save(String name, String password) { userdao.save(name, password); } }
package zhc.love.dj.Dao; public class UserDaoMSSqlImp implements UserDao { public void save(String name, String password) { System.out.println("----------MSSql.save()------------"); } }
package zhc.love.dj.test; import zhc.love.dj.Maneger.UserMangaer; public class Test { public static void main(String[] args){ UserMangaer.getInstance().save("zhangchao", "loveduanjing"); } }