代码之家  ›  专栏  ›  技术社区  ›  onemasse

C语言中有“设计模式”吗?[关闭]

  •  70
  • onemasse  · 技术社区  · 15 年前

    我知道设计模式通常是与面向对象编程相关的东西,但是你有没有在编写C语言时经常使用的模式?

    我对经典OO模式的简单翻译不感兴趣,请不要提及达夫的设备。;-)

    7 回复  |  直到 15 年前
        1
  •  77
  •   Joshua Schlichting    6 年前

    我最喜欢的是 Adam Tornhill :

    还有:我总是想到 goto 作为一个伟大的穷人的装饰图案的工具。

    :我强烈建议使用 生锈 ( rust-lang.org

        2
  •  9
  •   Vijay Mathew Chor-ming Lung    15 年前

    Design Patterns: Elements of Reusable Object-Oriented Software 国家:

    重要的是因为它影响一个人的 Simultals/C++-Lead语言特点, 这个选择决定了 而且不容易实现。 如果 我们假设程序语言 称为“继承”、“封装” 以及“多态性” 我们的模式直接由 不太常见的面向对象 例如,减少了 斜体矿

    斜体字的句子是你问题的答案。

        3
  •  6
  •   Edmund    15 年前

    通过回调实现多态性,例如标准库的 qsort 功能。它所需要的只是一种比较两个元素的方法,它可以对它们的数组进行排序。

    通过使用函数集(vtables)来表示类型的相关属性,以便泛型例程能够有效地处理它,您可以比这复杂得多。例如,读、写等调用打开的文件或网络端口。

        4
  •  5
  •   Vlad    15 年前

    示例(延迟初始化)

    #include <stdio.h>
    
    struct foo
    {
        int payload;
    };
    
    int calculate_payload()
    {
        printf("%s\n", "Performing lengthy initialization...");
        return 42;
    }
    
    struct foo *get_default_foo()
    {
        static int foo_calculated = 0;
        static struct foo default_foo;
        if (!foo_calculated) /* assuming single-threaded access */
        {
            foo_calculated = 1;
            default_foo.payload = calculate_payload();
        }
        return &default_foo;
    }
    
    int main()
    {
        struct foo *foo1, *foo2;
    
        printf("%s\n", "Starting the program");
    
        foo1 = get_default_foo();
        printf("%d\n", foo1->payload);
    
        foo2 = get_default_foo();
        printf("%d\n", foo2->payload);
    
        return 0;
    }
    
        6
  •  2
  •   Peter G.    15 年前

        7
  •  2
  •   nhahtdh Pankaj Wadhwa    13 年前

    虚拟文件系统是学习设计模式的完美范例。