2015年1月9日金曜日

開発環境

Head First Object-Oriented Analysis and Design: A Brain Friendly Guide to OOA&D (Brett McLaughlin (著)、 Gary Pollice (著)、 David West (著) 、 O'Reilly Media)のChapter 5. Good Design = Flexible Software: Give Your Software a 30-minute Workout、CODE MAGNETS(No. 3245)をC言語で考えてみる。

CODE MAGNETS(No. 3245)

コード(BBEdit, Emacs)

instrument_spec.h

#pragma once
#include "dict.h"

typedef struct instrument_spec {
  union {
    struct dictionary;
    dictionary properties;
  };
  void* (*get_property)(struct instrument_spec*, char const *);
  int (*matches)(struct instrument_spec*, struct instrument_spec*);
} instrument_spec;

instrument_spec *instrument_spec_new(void);
void instrument_spec_free(instrument_spec *in);
void* instrument_spec_get_property(instrument_spec *in, char const * name);
int instrument_spec_matches(instrument_spec *in, instrument_spec *other);

instrument_spec.ch

#include <stdlib.h>
#include "instrument_spec.h"

instrument_spec *instrument_spec_new(void) {
  instrument_spec *out = malloc(sizeof(instrument_spec));
  *out = (instrument_spec){.properties=*dictionary_new()};
  return out;
}

void instrument_spec_free(instrument_spec *in) {
  dictionary_free(&(in->properties));
  free(in);
}

void* instrument_spec_get_property(instrument_spec *in, char const * name) {
  if (in->get_property) {
    return in->get_property(in, name);    
  }
  return dictionary_find((dictionary const *)&(in->properties), name);
}

int instrument_spec_matches(instrument_spec *in, instrument_spec *other) {
  if (in->matches) {
    return in->matches(in, other);
  }
  for (int i = 0; i < in->length; i++)
    if (!instrument_spec_get_property(other, (char const *)in->pairs[i]))
      return 0;
  return 1;
}

入出力結果(Terminal)

$ make instrument_spec.o
clang ...
In file included from instrument_spec.c:2:
./instrument_spec.h:6:5: warning: anonymous structs are a Microsoft extension
      [-Wmicrosoft]
    struct dictionary;
    ^~~~~~
1 warning generated.
$

0 コメント:

コメントを投稿