工厂设计模式(Factory):

常规程序接口示例:

  1. interface IFood{
  2. void eat();
  3. }
  4. class Bread implements IFood{
  5. public void eat(){
  6. System.out.println("吃面包");
  7. }
  8. }
  9. class Untitled {
  10. public static void main(String[] args) {
  11. IFood food = new Bread();
  12. food.eat();
  13. }
  14. }

关键代码:IFood food = new Bread();
缺点:客户端需要明确的知道具体子类。如果更改别的需要更改客户端代码。
例如:

class Milk implements IFood{ public void eat(){ System.out.println(“喝牛奶”); }

class Untitled {

  1. public static void main(String[] args) {
  2. IFood food = new Milk();
  3. food.eat();
  4. }

}

将food实例化的对象从Bread->Milk。
工厂模式范例:

  1. interface IFood{
  2. void eat();
  3. }
  4. class Bread implements IFood{
  5. public void eat(){
  6. System.out.println("吃面包");
  7. }
  8. }
  9. class Milk implements IFood{
  10. public void eat(){
  11. System.out.println("喝牛奶");
  12. }
  13. }
  14. class Factory{
  15. public static IFood getInstance(String className){
  16. if ("bread".equals(className)) {
  17. return new Bread();
  18. }
  19. if ("milk".equals(className)) {
  20. return new Bread();
  21. }
  22. return null;
  23. }
  24. }
  25. class Untitled {
  26. public static void main(String[] args) {
  27. IFood food = Factory.getInstance(args[0]);
  28. food.eat();
  29. }
  30. }

总结:主类只关心工厂类和接口类,不需要关心实现接口的更多子类,达到降低耦合的目的。

代理设计模式(Proxy):

帮助用户将所有开发注意力只集中在核心业务功能上。
实现代理设计:

  1. interface IEat{
  2. void get();
  3. }
  4. class EatReal implements IEat{
  5. public void get(){
  6. System.out.println("真实主题:得到食物,开始品尝");
  7. }
  8. }
  9. class EatProxy implements IEat{
  10. private IEat eat;
  11. public void get(){
  12. this.prepare();
  13. this.eat.get();
  14. this.clear();
  15. }
  16. public EatProxy(IEat eat){
  17. this.eat = eat;
  18. }
  19. public void prepare(){
  20. System.out.println("1");
  21. System.out.println("2");
  22. System.out.println("3");
  23. }
  24. public void clear(){
  25. System.out.println("4");
  26. }
  27. }
  28. class Untitled {
  29. public static void main(String[] args) {
  30. IEat eat = new EatProxy(new EatReal());
  31. eat.get();
  32. /*
  33. 1
  34. 2
  35. 3
  36. 真实主题:得到食物,开始品尝
  37. 4
  38. */
  39. }
  40. }