JAVA中设计模式

 时间:2026-05-08 17:19:06

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中设计模式

  • 怎么使用AJAX的GET和POST异步请求
  • Postman如何测试接口
  • 如何将idea本地已有的新项目完整提交到gitlab上
  • mybatis 怎么将字符串转换成集合
  • git安装教程(详细)
  • 热门搜索
    什么是个人所得税 剃须刀什么牌子好 什么是网络 艾特是什么意思 契税是什么 厌氧菌是什么 人生的意义是什么 sc是什么管 人为什么会放屁 网上银行是什么