设计模式

本文深入探讨了工厂模式的设计理念,通过创建一个专门的类来负责产品实例的生成,从而实现职责的分离。文中提供了具体的代码示例,展示了如何使用工厂模式创建不同类型的产品,如苹果和葡萄。同时,也讨论了模式的优缺点,以及在实际应用中可能遇到的问题。

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

1.单例模式

2.工厂模式
  简介:
  核心思想:有一个专门的类来负责创建实例的过程。
  优缺点:模式的核心是工厂类,这个类负责产品的创建,而客户端可以免去产品创建的责任,这实现了责任的分割。但由于工厂类集中了所有产品创建逻辑的,如果不能正常工作的话会对系统造成很大的影响。如果增加新产品必须修改工厂角色的源码。
  设计:1个接口类,若干个实现该接口的实现类,1个工厂类(工厂类实行调控功能,负责判断、控制哪个实现类被执行。工厂方法一般都是static的)。

代码:

public interface Fruit { 
     void grow();//生长
     void harvest();//收获 
     void plant();//种植
}

public class Apple implements Fruit{ 
    private int treeAge;
    public void grow() { 
        System.out.println("Apple is growing");
    }
    public void harvest() { 
        System.out.println("Apple has been harvested");
    }
    public void plant() { 
        System.out.println("Apple has been planted");
    }
    public int getTreeAge() {  
        return treeAge; 
    }
    public void setTreeAge(int age) {  
        this.treeAge=age; 
    }
}

public class Grape implements Fruit { 
    private boolean seedless; 
    public void grow() {  
        System.out.println("Apple is growing"); 
    } 
    public void harvest() {  
        System.out.println("Apple has been harvested"); 
    } 
    public void plant() {  
        System.out.println("Apple has been planted"); 
    } 
    public boolean getSeedless() {  
        return seedless; 
    } 
    public void setSeedless(boolean seed) {  
        this.seedless=seed; 
    }
}

public class FruitGardener { 
    public static Fruit factory(String which) throws BadFruitException {  
        if(which.equalsIgnoreCase("apple搜索"))  {   
            return new Apple();  
        } else if (which.equalsIgnoreCase("grape"))  {   
            return new Grape();  
        }  else {   
            throw new BadFruitException("Bad Fruit request");  
        }    
    }
}

public class BadFruitException extends Exception{ 
    public BadFruitException(String msg) {  
        super(msg); 
    }
}

public static void main(String[] args) { 
    try {  
        FruitGardener.factory("apple");  
        FruitGardener.factory("grape"); 
    } catch(BadFruitException e) {          
        System.out.println(e); 
    }     
}

 

转载于:https://www.cnblogs.com/thinksasa/p/4221093.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值