手抄报 安全手抄报 手抄报内容 生活知识 生活百科 英语手抄报 清明节手抄报 节约用水手抄报 知识问答

JAVA中设计模式

时间:2026-02-26 17:10:28

1、观察下面程序:

定义一个接口

interface   Fruit{

    public void eat();

}

主方法实际上就相当于一个客户端;

JAVA中设计模式

2、class  Apple  implements  Fruit{

       public void eat(){

          System.out.println("吃苹果");

}

}

JAVA中设计模式

3、class  Orange   implements  Fruit {

    public void  eat(){

       System.out.println("吃橘子");

}

}

public  class  interfaceDemo(){

   public  static  void  main(String args[]){

       Fruit  f=new Apple();

        f.eat();

}

}

实现Fruit接口,如果此时需要更换一个子类,子必须要修改主方法

JAVA中设计模式

1、工厂设计模式:

interface   Fruit{

    public void eat();

}

class  Apple  implements  Fruit{

       public void eat(){

          System.out.println("吃苹果");

}

}

class  Orange   implements  Fruit {

    public void  eat(){

       System.out.println("吃橘子");

}

}

JAVA中设计模式

2、class  Factory{

   public   static  Fruit  getInstance(String   className){

        Fruit   f=null;

        if(“apple”.equals(className)){

           f=new  apple();

        }

        if("orange".equals(className)){

          f=new Orange();

        }

         return  f;

}

}

JAVA中设计模式

3、public   class   interfaceDemo{

      public  static  void   main{String   args[]}{

           Fruit  f=null;定义 接口对象

           f =Factory.getInstance("apple");

           f.eat();

      }

}

程序在接口和子类之间加入一个过渡端,通过此过度端取得接口的实例化对象

一般都会称这个过度端为工厂类;

JAVA中设计模式

© 2026 手抄报圈
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com