Java 简单工厂模式

工厂模式的应用很广泛,精髓之处在于通过工厂类来获取对象,而不是直接创造对象,这样的好处在于不依赖要创建的具体对象类型,以达到解耦的目的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class TestFactory {
    public static void main(String[] args) {
        //使用者与被使用者之间产生了耦合,依赖。当被使用者改变时,会影响使用者。
//      Phone ph = new Phone();
//      ph.work();
        Product p = new ProductFactory().getProduct("phone");
        if(p!=null) {
            p.work();
        }
    }
}
 
class ProductFactory{
    public Product getProduct(String name) {
        if(name.equals("phone")) {
            return new Phone();
        }
        else if(name.equals("computer")) {
            return new Computer();
        }
        return null;
    }
}
 
interface Product{
    public void work();
}
 
class Phone implements Product{
    public void work() {
        System.out.println("生产手机");
    }
}
 
class Computer implements Product{
    public void work() {
        System.out.println("生产电脑");
    }
}

 

posted @   藤原豆腐渣渣  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示