工厂方法模式

本文介绍工厂方法模式的基本概念,包括抽象工厂类、具体工厂类、抽象产品类和具体产品类等核心成员。通过示例代码展示了如何使用该模式创建不同类型的产品实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一. 工厂方法的成员

1. 抽象工厂类:提供具体工厂的类或者接口

2. 具体工厂类:抽象工厂类的具体实现

3. 抽象产品类:提供具体产品的类或者接口

4. 具体产品类:抽象产品类的具体实现

二. 例子(网上找的,感觉很好的例子)

// 抽象工厂方法

public interface AbstractFactory {

      public Plant createPlant();

      public Fruit createFruit() ;

}


//具体工厂方法
 
public class FactoryA implements AbstractFactory {


           
public Plant createPlant() {

      return new PlantA();

  }

     public Fruit createFruit() {

        return new FruitA();
 
  }
}

public class FactoryB implements AbstractFactory {

     public Plant createPlant() {
 
        return new PlantB();
  
  }

   public Fruit createFruit() {

    return new FruitB();

  }
}


// 产品 Plant接口

public interface Plant { }

//具体产品PlantA,PlantB

public class PlantA implements Plant {

            public PlantA () {

            System.out.println("create PlantA !");
            }

          public void doSomething() {

                    System.out.println(" PlantA do something ...");
        }
}

public class PlantB implements Plant {

  public PlantB () {

  System.out.println("create PlantB !");

    }

     public void doSomething() {

                 System.out.println(" PlantB do something ...");
 
  }

}

// 产品 Fruit接口

public interface Fruit { }

//具体产品FruitA,FruitB

public class FruitA implements Fruit {

             public FruitA() {

                  System.out.println("create FruitA !");
       }
     

          public void doSomething() {

                   System.out.println(" FruitA do something ...");
      }
}


public class FruitB implements Fruit {

  public FruitB() {

            System.out.println("create FruitB !");

      }

  public void doSomething() {

                System.out.println(" FruitB do something ...");

  }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值