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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="generator" content="hevea 2.32">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<link rel="stylesheet" type="text/css" href="manual.css">
<title>Chapter 6 Advanced examples with classes and modules</title>
</head>
<body>
<a href="polymorphism.html"><img src="previous_motif.svg" alt="Previous"></a>
<a href="index.html"><img src="contents_motif.svg" alt="Up"></a>
<a href="language.html"><img src="next_motif.svg" alt="Next"></a>
<hr>
<h1 class="chapter" id="sec64">Chapter 6 Advanced examples with classes and modules</h1>
<ul>
<li><a href="advexamples.html#s%3Aextended-bank-accounts">6.1 Extended example: bank accounts</a>
</li><li><a href="advexamples.html#s%3Amodules-as-classes">6.2 Simple modules as classes</a>
</li><li><a href="advexamples.html#s%3Asubject-observer">6.3 The subject/observer pattern</a>
</li></ul>
<p>
<a id="c:advexamples"></a></p><p><span class="c009">(Chapter written by Didier Rémy)</span></p><p><br>
<br>
</p><p>In this chapter, we show some larger examples using objects, classes
and modules. We review many of the object features simultaneously on
the example of a bank account. We show how modules taken from the
standard library can be expressed as classes. Lastly, we describe a
programming pattern known as <em>virtual types</em> through the example
of window managers.</p>
<h2 class="section" id="s:extended-bank-accounts"><a class="section-anchor" href="#s:extended-bank-accounts" aria-hidden="true"></a>6.1 Extended example: bank accounts</h2>
<p>In this section, we illustrate most aspects of Object and inheritance
by refining, debugging, and specializing the following
initial naive definition of a simple bank account. (We reuse the
module <span class="c003">Euro</span> defined at the end of chapter <a href="objectexamples.html#c%3Aobjectexamples">3</a>.)
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> euro = <span class="ocamlkeyword">new</span> Euro.c;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> euro : float -> Euro.c = <<span class="ocamlkeyword">fun</span>></div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> zero = euro 0.;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> zero : Euro.c = <obj></div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> neg x = x#times (-1.);;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> neg : < times : float -> 'a; .. > -> 'a = <<span class="ocamlkeyword">fun</span>></div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> account =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> balance = zero
<span class="ocamlkeyword">method</span> balance = balance
<span class="ocamlkeyword">method</span> deposit x = balance <- balance # plus x
<span class="ocamlkeyword">method</span> withdraw x =
<span class="ocamlkeyword">if</span> x#leq balance <span class="ocamlkeyword">then</span> (balance <- balance # plus (neg x); x) <span class="ocamlkeyword">else</span> zero
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> account :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> balance : Euro.c
<span class="ocamlkeyword">method</span> balance : Euro.c
<span class="ocamlkeyword">method</span> deposit : Euro.c -> unit
<span class="ocamlkeyword">method</span> withdraw : Euro.c -> Euro.c
<span class="ocamlkeyword">end</span></div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> c = <span class="ocamlkeyword">new</span> account <span class="ocamlkeyword">in</span> c # deposit (euro 100.); c # withdraw (euro 50.);;</div>
<div class="pre caml-output ok">- : Euro.c = <obj></div></div>
</div><p>
We now refine this definition with a method to compute interest.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> account_with_interests =
<span class="ocamlkeyword">object</span> (self)
<span class="ocamlkeyword">inherit</span> account
<span class="ocamlkeyword">method</span> <span class="ocamlkeyword">private</span> interest = self # deposit (self # balance # times 0.03)
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> account_with_interests :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> balance : Euro.c
<span class="ocamlkeyword">method</span> balance : Euro.c
<span class="ocamlkeyword">method</span> deposit : Euro.c -> unit
<span class="ocamlkeyword">method</span> <span class="ocamlkeyword">private</span> interest : unit
<span class="ocamlkeyword">method</span> withdraw : Euro.c -> Euro.c
<span class="ocamlkeyword">end</span></div></div>
</div><p>
We make the method <span class="c003">interest</span> private, since clearly it should not be
called freely from the outside. Here, it is only made accessible to subclasses
that will manage monthly or yearly updates of the account.</p><p>We should soon fix a bug in the current definition: the deposit method can
be used for withdrawing money by depositing negative amounts. We can
fix this directly:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> safe_account =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> account
<span class="ocamlkeyword">method</span> deposit x = <span class="ocamlkeyword">if</span> zero#leq x <span class="ocamlkeyword">then</span> balance <- balance#plus x
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> safe_account :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> balance : Euro.c
<span class="ocamlkeyword">method</span> balance : Euro.c
<span class="ocamlkeyword">method</span> deposit : Euro.c -> unit
<span class="ocamlkeyword">method</span> withdraw : Euro.c -> Euro.c
<span class="ocamlkeyword">end</span></div></div>
</div><p>
However, the bug might be fixed more safely by the following definition:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> safe_account =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> account <span class="ocamlkeyword">as</span> unsafe
<span class="ocamlkeyword">method</span> deposit x =
<span class="ocamlkeyword">if</span> zero#leq x <span class="ocamlkeyword">then</span> unsafe # deposit x
<span class="ocamlkeyword">else</span> raise (Invalid_argument <span class="ocamlstring">"deposit"</span>)
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> safe_account :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> balance : Euro.c
<span class="ocamlkeyword">method</span> balance : Euro.c
<span class="ocamlkeyword">method</span> deposit : Euro.c -> unit
<span class="ocamlkeyword">method</span> withdraw : Euro.c -> Euro.c
<span class="ocamlkeyword">end</span></div></div>
</div><p>
In particular, this does not require the knowledge of the implementation of
the method <span class="c003">deposit</span>.</p><p>To keep track of operations, we extend the class with a mutable field
<span class="c003">history</span> and a private method <span class="c003">trace</span> to add an operation in the
log. Then each method to be traced is redefined.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">type</span> 'a operation = Deposit <span class="ocamlkeyword">of</span> 'a | Retrieval <span class="ocamlkeyword">of</span> 'a;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">type</span> 'a operation = Deposit <span class="ocamlkeyword">of</span> 'a | Retrieval <span class="ocamlkeyword">of</span> 'a</div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> account_with_history =
<span class="ocamlkeyword">object</span> (self)
<span class="ocamlkeyword">inherit</span> safe_account <span class="ocamlkeyword">as</span> super
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> history = []
<span class="ocamlkeyword">method</span> <span class="ocamlkeyword">private</span> trace x = history <- x :: history
<span class="ocamlkeyword">method</span> deposit x = self#trace (Deposit x); super#deposit x
<span class="ocamlkeyword">method</span> withdraw x = self#trace (Retrieval x); super#withdraw x
<span class="ocamlkeyword">method</span> history = List.rev history
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> account_with_history :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> balance : Euro.c
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> history : Euro.c operation list
<span class="ocamlkeyword">method</span> balance : Euro.c
<span class="ocamlkeyword">method</span> deposit : Euro.c -> unit
<span class="ocamlkeyword">method</span> history : Euro.c operation list
<span class="ocamlkeyword">method</span> <span class="ocamlkeyword">private</span> trace : Euro.c operation -> unit
<span class="ocamlkeyword">method</span> withdraw : Euro.c -> Euro.c
<span class="ocamlkeyword">end</span></div></div>
</div><p>
One may wish to open an account and simultaneously deposit some initial
amount. Although the initial implementation did not address this
requirement, it can be achieved by using an initializer.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> account_with_deposit x =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> account_with_history
<span class="ocamlkeyword">initializer</span> balance <- x
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> account_with_deposit :
Euro.c ->
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> balance : Euro.c
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> history : Euro.c operation list
<span class="ocamlkeyword">method</span> balance : Euro.c
<span class="ocamlkeyword">method</span> deposit : Euro.c -> unit
<span class="ocamlkeyword">method</span> history : Euro.c operation list
<span class="ocamlkeyword">method</span> <span class="ocamlkeyword">private</span> trace : Euro.c operation -> unit
<span class="ocamlkeyword">method</span> withdraw : Euro.c -> Euro.c
<span class="ocamlkeyword">end</span></div></div>
</div><p>
A better alternative is:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> account_with_deposit x =
<span class="ocamlkeyword">object</span> (self)
<span class="ocamlkeyword">inherit</span> account_with_history
<span class="ocamlkeyword">initializer</span> self#deposit x
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> account_with_deposit :
Euro.c ->
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> balance : Euro.c
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> history : Euro.c operation list
<span class="ocamlkeyword">method</span> balance : Euro.c
<span class="ocamlkeyword">method</span> deposit : Euro.c -> unit
<span class="ocamlkeyword">method</span> history : Euro.c operation list
<span class="ocamlkeyword">method</span> <span class="ocamlkeyword">private</span> trace : Euro.c operation -> unit
<span class="ocamlkeyword">method</span> withdraw : Euro.c -> Euro.c
<span class="ocamlkeyword">end</span></div></div>
</div><p>
Indeed, the latter is safer since the call to <span class="c003">deposit</span> will automatically
benefit from safety checks and from the trace.
Let’s test it:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> ccp = <span class="ocamlkeyword">new</span> account_with_deposit (euro 100.) <span class="ocamlkeyword">in</span>
<span class="ocamlkeyword">let</span> _balance = ccp#withdraw (euro 50.) <span class="ocamlkeyword">in</span>
ccp#history;;</div>
<div class="pre caml-output ok">- : Euro.c operation list = [Deposit <obj>; Retrieval <obj>]</div></div>
</div><p>
Closing an account can be done with the following polymorphic function:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> close c = c#withdraw c#balance;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> close : < balance : 'a; withdraw : 'a -> 'b; .. > -> 'b = <<span class="ocamlkeyword">fun</span>></div></div>
</div><p>
Of course, this applies to all sorts of accounts.</p><p>Finally, we gather several versions of the account into a module <span class="c003">Account</span>
abstracted over some currency.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> today () = (01,01,2000) <span class="ocamlcomment">(* an approximation *)</span>
<span class="ocamlkeyword">module</span> Account (M:MONEY) =
<span class="ocamlkeyword">struct</span>
<span class="ocamlkeyword">type</span> m = M.c
<span class="ocamlkeyword">let</span> m = <span class="ocamlkeyword">new</span> M.c
<span class="ocamlkeyword">let</span> zero = m 0.
<span class="ocamlkeyword">class</span> bank =
<span class="ocamlkeyword">object</span> (self)
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> balance = zero
<span class="ocamlkeyword">method</span> balance = balance
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> history = []
<span class="ocamlkeyword">method</span> <span class="ocamlkeyword">private</span> trace x = history <- x::history
<span class="ocamlkeyword">method</span> deposit x =
self#trace (Deposit x);
<span class="ocamlkeyword">if</span> zero#leq x <span class="ocamlkeyword">then</span> balance <- balance # plus x
<span class="ocamlkeyword">else</span> raise (Invalid_argument <span class="ocamlstring">"deposit"</span>)
<span class="ocamlkeyword">method</span> withdraw x =
<span class="ocamlkeyword">if</span> x#leq balance <span class="ocamlkeyword">then</span>
(balance <- balance # plus (neg x); self#trace (Retrieval x); x)
<span class="ocamlkeyword">else</span> zero
<span class="ocamlkeyword">method</span> history = List.rev history
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">class</span> <span class="ocamlkeyword">type</span> client_view =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">method</span> deposit : m -> unit
<span class="ocamlkeyword">method</span> history : m operation list
<span class="ocamlkeyword">method</span> withdraw : m -> m
<span class="ocamlkeyword">method</span> balance : m
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">class</span> <span class="ocamlkeyword">virtual</span> check_client x =
<span class="ocamlkeyword">let</span> y = <span class="ocamlkeyword">if</span> (m 100.)#leq x <span class="ocamlkeyword">then</span> x
<span class="ocamlkeyword">else</span> raise (Failure <span class="ocamlstring">"Insufficient initial deposit"</span>) <span class="ocamlkeyword">in</span>
<span class="ocamlkeyword">object</span> (self)
<span class="ocamlkeyword">initializer</span> self#deposit y
<span class="ocamlkeyword">method</span> <span class="ocamlkeyword">virtual</span> deposit: m -> unit
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">module</span> Client (B : <span class="ocamlkeyword">sig</span> <span class="ocamlkeyword">class</span> bank : client_view <span class="ocamlkeyword">end</span>) =
<span class="ocamlkeyword">struct</span>
<span class="ocamlkeyword">class</span> account x : client_view =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> B.bank
<span class="ocamlkeyword">inherit</span> check_client x
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">let</span> discount x =
<span class="ocamlkeyword">let</span> c = <span class="ocamlkeyword">new</span> account x <span class="ocamlkeyword">in</span>
<span class="ocamlkeyword">if</span> today() < (1998,10,30) <span class="ocamlkeyword">then</span> c # deposit (m 100.); c
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">end</span>;;</div></div>
</div><p>
This shows the use of modules to group several class definitions that can in
fact be thought of as a single unit. This unit would be provided by a bank
for both internal and external uses.
This is implemented as a functor that abstracts over the currency so that
the same code can be used to provide accounts in different currencies.</p><p>The class <span class="c003">bank</span> is the <em>real</em> implementation of the bank account (it
could have been inlined). This is the one that will be used for further
extensions, refinements, etc. Conversely, the client will only be given the client view.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">module</span> Euro_account = Account(Euro);;</div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">module</span> Client = Euro_account.Client (Euro_account);;</div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">new</span> Client.account (<span class="ocamlkeyword">new</span> Euro.c 100.);;</div></div>
</div><p>
Hence, the clients do not have direct access to the <span class="c003">balance</span>, nor the
<span class="c003">history</span> of their own accounts. Their only way to change their balance is
to deposit or withdraw money. It is important to give the clients
a class and not just the ability to create accounts (such as the
promotional <span class="c003">discount</span> account), so that they can
personalize their account.
For instance, a client may refine the <span class="c003">deposit</span> and <span class="c003">withdraw</span> methods
so as to do his own financial bookkeeping, automatically. On the
other hand, the function <span class="c003">discount</span> is given as such, with no
possibility for further personalization.</p><p>It is important to provide the client’s view as a functor
<span class="c003">Client</span> so that client accounts can still be built after a possible
specialization of the <span class="c003">bank</span>.
The functor <span class="c003">Client</span> may remain unchanged and be passed
the new definition to initialize a client’s view of the extended account.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">module</span> Investment_account (M : MONEY) =
<span class="ocamlkeyword">struct</span>
<span class="ocamlkeyword">type</span> m = M.c
<span class="ocamlkeyword">module</span> A = Account(M)
<span class="ocamlkeyword">class</span> bank =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> A.bank <span class="ocamlkeyword">as</span> super
<span class="ocamlkeyword">method</span> deposit x =
<span class="ocamlkeyword">if</span> (<span class="ocamlkeyword">new</span> M.c 1000.)#leq x <span class="ocamlkeyword">then</span>
print_string <span class="ocamlstring">"Would you like to invest?"</span>;
super#deposit x
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">module</span> Client = A.Client
<span class="ocamlkeyword">end</span>;;</div></div>
</div><p>
The functor <span class="c003">Client</span> may also be redefined when some new features of the
account can be given to the client.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">module</span> Internet_account (M : MONEY) =
<span class="ocamlkeyword">struct</span>
<span class="ocamlkeyword">type</span> m = M.c
<span class="ocamlkeyword">module</span> A = Account(M)
<span class="ocamlkeyword">class</span> bank =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> A.bank
<span class="ocamlkeyword">method</span> mail s = print_string s
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">class</span> <span class="ocamlkeyword">type</span> client_view =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">method</span> deposit : m -> unit
<span class="ocamlkeyword">method</span> history : m operation list
<span class="ocamlkeyword">method</span> withdraw : m -> m
<span class="ocamlkeyword">method</span> balance : m
<span class="ocamlkeyword">method</span> mail : string -> unit
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">module</span> Client (B : <span class="ocamlkeyword">sig</span> <span class="ocamlkeyword">class</span> bank : client_view <span class="ocamlkeyword">end</span>) =
<span class="ocamlkeyword">struct</span>
<span class="ocamlkeyword">class</span> account x : client_view =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> B.bank
<span class="ocamlkeyword">inherit</span> A.check_client x
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">end</span>;;</div></div>
</div>
<h2 class="section" id="s:modules-as-classes"><a class="section-anchor" href="#s:modules-as-classes" aria-hidden="true"></a>6.2 Simple modules as classes</h2>
<p>One may wonder whether it is possible to treat primitive types such as
integers and strings as objects. Although this is usually uninteresting
for integers or strings, there may be some situations where
this is desirable. The class <span class="c003">money</span> above is such an example.
We show here how to do it for strings.</p>
<h3 class="subsection" id="ss:string-as-class"><a class="section-anchor" href="#ss:string-as-class" aria-hidden="true"></a>6.2.1 Strings</h3>
<p>A naive definition of strings as objects could be:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ostring s =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">method</span> get n = String.get s n
<span class="ocamlkeyword">method</span> print = print_string s
<span class="ocamlkeyword">method</span> escaped = <span class="ocamlkeyword">new</span> ostring (String.escaped s)
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ostring :
string ->
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">method</span> escaped : ostring
<span class="ocamlkeyword">method</span> get : int -> char
<span class="ocamlkeyword">method</span> print : unit
<span class="ocamlkeyword">end</span></div></div>
</div><p>
However, the method <span class="c003">escaped</span> returns an object of the class <span class="c003">ostring</span>,
and not an object of the current class. Hence, if the class is further
extended, the method <span class="c003">escaped</span> will only return an object of the parent
class.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> sub_string s =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> ostring s
<span class="ocamlkeyword">method</span> sub start len = <span class="ocamlkeyword">new</span> sub_string (String.sub s start len)
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> sub_string :
string ->
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">method</span> escaped : ostring
<span class="ocamlkeyword">method</span> get : int -> char
<span class="ocamlkeyword">method</span> print : unit
<span class="ocamlkeyword">method</span> sub : int -> int -> sub_string
<span class="ocamlkeyword">end</span></div></div>
</div><p>
As seen in section <a href="objectexamples.html#s%3Abinary-methods">3.16</a>, the solution is to use
functional update instead. We need to create an instance variable
containing the representation <span class="c003">s</span> of the string.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> better_string s =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> repr = s
<span class="ocamlkeyword">method</span> get n = String.get repr n
<span class="ocamlkeyword">method</span> print = print_string repr
<span class="ocamlkeyword">method</span> escaped = {< repr = String.escaped repr >}
<span class="ocamlkeyword">method</span> sub start len = {< repr = String.sub s start len >}
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> better_string :
string ->
<span class="ocamlkeyword">object</span> ('a)
<span class="ocamlkeyword">val</span> repr : string
<span class="ocamlkeyword">method</span> escaped : 'a
<span class="ocamlkeyword">method</span> get : int -> char
<span class="ocamlkeyword">method</span> print : unit
<span class="ocamlkeyword">method</span> sub : int -> int -> 'a
<span class="ocamlkeyword">end</span></div></div>
</div><p>
As shown in the inferred type, the methods <span class="c003">escaped</span> and <span class="c003">sub</span> now return
objects of the same type as the one of the class.</p><p>Another difficulty is the implementation of the method <span class="c003">concat</span>.
In order to concatenate a string with another string of the same class,
one must be able to access the instance variable externally. Thus, a method
<span class="c003">repr</span> returning s must be defined. Here is the correct definition of
strings:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ostring s =
<span class="ocamlkeyword">object</span> (self : 'mytype)
<span class="ocamlkeyword">val</span> repr = s
<span class="ocamlkeyword">method</span> repr = repr
<span class="ocamlkeyword">method</span> get n = String.get repr n
<span class="ocamlkeyword">method</span> print = print_string repr
<span class="ocamlkeyword">method</span> escaped = {< repr = String.escaped repr >}
<span class="ocamlkeyword">method</span> sub start len = {< repr = String.sub s start len >}
<span class="ocamlkeyword">method</span> concat (t : 'mytype) = {< repr = repr ^ t#repr >}
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ostring :
string ->
<span class="ocamlkeyword">object</span> ('a)
<span class="ocamlkeyword">val</span> repr : string
<span class="ocamlkeyword">method</span> concat : 'a -> 'a
<span class="ocamlkeyword">method</span> escaped : 'a
<span class="ocamlkeyword">method</span> get : int -> char
<span class="ocamlkeyword">method</span> print : unit
<span class="ocamlkeyword">method</span> repr : string
<span class="ocamlkeyword">method</span> sub : int -> int -> 'a
<span class="ocamlkeyword">end</span></div></div>
</div><p>
Another constructor of the class string can be defined to return a new
string of a given length:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> cstring n = ostring (String.make n ' ');;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> cstring : int -> ostring</div></div>
</div><p>
Here, exposing the representation of strings is probably harmless. We do
could also hide the representation of strings as we hid the currency in the
class <span class="c003">money</span> of section <a href="objectexamples.html#s%3Afriends">3.17</a>.</p>
<h4 class="subsubsection" id="sss:stack-as-class"><a class="section-anchor" href="#sss:stack-as-class" aria-hidden="true"></a>Stacks</h4>
<p>There is sometimes an alternative between using modules or classes for
parametric data types.
Indeed, there are situations when the two approaches are quite similar.
For instance, a stack can be straightforwardly implemented as a class:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">exception</span> Empty;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">exception</span> Empty</div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['a] stack =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> l = ([] : 'a list)
<span class="ocamlkeyword">method</span> push x = l <- x::l
<span class="ocamlkeyword">method</span> pop = <span class="ocamlkeyword">match</span> l <span class="ocamlkeyword">with</span> [] -> raise Empty | a::l' -> l <- l'; a
<span class="ocamlkeyword">method</span> clear = l <- []
<span class="ocamlkeyword">method</span> length = List.length l
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a] stack :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> l : 'a list
<span class="ocamlkeyword">method</span> clear : unit
<span class="ocamlkeyword">method</span> length : int
<span class="ocamlkeyword">method</span> pop : 'a
<span class="ocamlkeyword">method</span> push : 'a -> unit
<span class="ocamlkeyword">end</span></div></div>
</div><p>
However, writing a method for iterating over a stack is more
problematic. A method <span class="c003">fold</span> would have type
<span class="c003">('b -> 'a -> 'b) -> 'b -> 'b</span>. Here <span class="c003">'a</span> is the parameter of the stack.
The parameter <span class="c003">'b</span> is not related to the class <span class="c003">'a stack</span> but to the
argument that will be passed to the method <span class="c003">fold</span>.
A naive approach is to make <span class="c003">'b</span> an extra parameter of class <span class="c003">stack</span>:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['a, 'b] stack2 =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> ['a] stack
<span class="ocamlkeyword">method</span> fold f (x : 'b) = List.fold_left f x l
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a, 'b] stack2 :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> l : 'a list
<span class="ocamlkeyword">method</span> clear : unit
<span class="ocamlkeyword">method</span> fold : ('b -> 'a -> 'b) -> 'b -> 'b
<span class="ocamlkeyword">method</span> length : int
<span class="ocamlkeyword">method</span> pop : 'a
<span class="ocamlkeyword">method</span> push : 'a -> unit
<span class="ocamlkeyword">end</span></div></div>
</div><p>
However, the method <span class="c003">fold</span> of a given object can only be
applied to functions that all have the same type:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> s = <span class="ocamlkeyword">new</span> stack2;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> s : ('_weak1, '_weak2) stack2 = <obj></div></div>
<div class="ocaml">
<div class="pre caml-input"> s#fold ( + ) 0;;</div>
<div class="pre caml-output ok">- : int = 0</div></div>
<div class="ocaml">
<div class="pre caml-input"> s;;</div>
<div class="pre caml-output ok">- : (int, int) stack2 = <obj></div></div>
</div><p>
A better solution is to use polymorphic methods, which were
introduced in OCaml version 3.05. Polymorphic methods makes
it possible to treat the type variable <span class="c003">'b</span> in the type of <span class="c003">fold</span> as
universally quantified, giving <span class="c003">fold</span> the polymorphic type
<span class="c003">Forall 'b. ('b -> 'a -> 'b) -> 'b -> 'b</span>.
An explicit type declaration on the method <span class="c003">fold</span> is required, since
the type checker cannot infer the polymorphic type by itself.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['a] stack3 =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> ['a] stack
<span class="ocamlkeyword">method</span> fold : 'b. ('b -> 'a -> 'b) -> 'b -> 'b
= <span class="ocamlkeyword">fun</span> f x -> List.fold_left f x l
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a] stack3 :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> l : 'a list
<span class="ocamlkeyword">method</span> clear : unit
<span class="ocamlkeyword">method</span> fold : ('b -> 'a -> 'b) -> 'b -> 'b
<span class="ocamlkeyword">method</span> length : int
<span class="ocamlkeyword">method</span> pop : 'a
<span class="ocamlkeyword">method</span> push : 'a -> unit
<span class="ocamlkeyword">end</span></div></div>
</div>
<h3 class="subsection" id="ss:hashtbl-as-class"><a class="section-anchor" href="#ss:hashtbl-as-class" aria-hidden="true"></a>6.2.2 Hashtbl</h3>
<p>A simplified version of object-oriented hash tables should have the
following class type.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> <span class="ocamlkeyword">type</span> ['a, 'b] hash_table =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">method</span> find : 'a -> 'b
<span class="ocamlkeyword">method</span> add : 'a -> 'b -> unit
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> <span class="ocamlkeyword">type</span> ['a, 'b] hash_table =
<span class="ocamlkeyword">object</span> <span class="ocamlkeyword">method</span> add : 'a -> 'b -> unit <span class="ocamlkeyword">method</span> find : 'a -> 'b <span class="ocamlkeyword">end</span></div></div>
</div><p>
A simple implementation, which is quite reasonable for small hash tables is
to use an association list:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['a, 'b] small_hashtbl : ['a, 'b] hash_table =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> table = []
<span class="ocamlkeyword">method</span> find key = List.assoc key table
<span class="ocamlkeyword">method</span> add key valeur = table <- (key, valeur) :: table
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a, 'b] small_hashtbl : ['a, 'b] hash_table</div></div>
</div><p>
A better implementation, and one that scales up better, is to use a
true hash table… whose elements are small hash tables!
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['a, 'b] hashtbl size : ['a, 'b] hash_table =
<span class="ocamlkeyword">object</span> (self)
<span class="ocamlkeyword">val</span> table = Array.init size (<span class="ocamlkeyword">fun</span> i -> <span class="ocamlkeyword">new</span> small_hashtbl)
<span class="ocamlkeyword">method</span> <span class="ocamlkeyword">private</span> hash key =
(Hashtbl.hash key) <span class="ocamlkeyword">mod</span> (Array.length table)
<span class="ocamlkeyword">method</span> find key = table.(self#hash key) # find key
<span class="ocamlkeyword">method</span> add key = table.(self#hash key) # add key
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a, 'b] hashtbl : int -> ['a, 'b] hash_table</div></div>
</div>
<h3 class="subsection" id="ss:set-as-class"><a class="section-anchor" href="#ss:set-as-class" aria-hidden="true"></a>6.2.3 Sets</h3>
<p>Implementing sets leads to another difficulty. Indeed, the method
<span class="c003">union</span> needs to be able to access the internal representation of
another object of the same class.</p><p>This is another instance of friend functions as seen in
section <a href="objectexamples.html#s%3Afriends">3.17</a>. Indeed, this is the same mechanism used in the module
<span class="c003">Set</span> in the absence of objects.</p><p>In the object-oriented version of sets, we only need to add an additional
method <span class="c003">tag</span> to return the representation of a set. Since sets are
parametric in the type of elements, the method <span class="c003">tag</span> has a parametric type
<span class="c003">'a tag</span>, concrete within
the module definition but abstract in its signature.
From outside, it will then be guaranteed that two objects with a method <span class="c003">tag</span>
of the same type will share the same representation.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">module</span> <span class="ocamlkeyword">type</span> SET =
<span class="ocamlkeyword">sig</span>
<span class="ocamlkeyword">type</span> 'a tag
<span class="ocamlkeyword">class</span> ['a] c :
<span class="ocamlkeyword">object</span> ('b)
<span class="ocamlkeyword">method</span> is_empty : bool
<span class="ocamlkeyword">method</span> mem : 'a -> bool
<span class="ocamlkeyword">method</span> add : 'a -> 'b
<span class="ocamlkeyword">method</span> union : 'b -> 'b
<span class="ocamlkeyword">method</span> iter : ('a -> unit) -> unit
<span class="ocamlkeyword">method</span> tag : 'a tag
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">end</span>;;</div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">module</span> Set : SET =
<span class="ocamlkeyword">struct</span>
<span class="ocamlkeyword">let</span> <span class="ocamlkeyword">rec</span> merge l1 l2 =
<span class="ocamlkeyword">match</span> l1 <span class="ocamlkeyword">with</span>
[] -> l2
| h1 :: t1 ->
<span class="ocamlkeyword">match</span> l2 <span class="ocamlkeyword">with</span>
[] -> l1
| h2 :: t2 ->
<span class="ocamlkeyword">if</span> h1 < h2 <span class="ocamlkeyword">then</span> h1 :: merge t1 l2
<span class="ocamlkeyword">else</span> <span class="ocamlkeyword">if</span> h1 > h2 <span class="ocamlkeyword">then</span> h2 :: merge l1 t2
<span class="ocamlkeyword">else</span> merge t1 l2
<span class="ocamlkeyword">type</span> 'a tag = 'a list
<span class="ocamlkeyword">class</span> ['a] c =
<span class="ocamlkeyword">object</span> (_ : 'b)
<span class="ocamlkeyword">val</span> repr = ([] : 'a list)
<span class="ocamlkeyword">method</span> is_empty = (repr = [])
<span class="ocamlkeyword">method</span> mem x = List.exists (( = ) x) repr
<span class="ocamlkeyword">method</span> add x = {< repr = merge [x] repr >}
<span class="ocamlkeyword">method</span> union (s : 'b) = {< repr = merge repr s#tag >}
<span class="ocamlkeyword">method</span> iter (f : 'a -> unit) = List.iter f repr
<span class="ocamlkeyword">method</span> tag = repr
<span class="ocamlkeyword">end</span>
<span class="ocamlkeyword">end</span>;;</div></div>
</div>
<h2 class="section" id="s:subject-observer"><a class="section-anchor" href="#s:subject-observer" aria-hidden="true"></a>6.3 The subject/observer pattern</h2>
<p>The following example, known as the subject/observer pattern, is often
presented in the literature as a difficult inheritance problem with
inter-connected classes.
The general pattern amounts to the definition a pair of two
classes that recursively interact with one another.</p><p>The class <span class="c003">observer</span> has a distinguished method <span class="c003">notify</span> that requires
two arguments, a subject and an event to execute an action.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> <span class="ocamlkeyword">virtual</span> ['subject, 'event] observer =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">method</span> <span class="ocamlkeyword">virtual</span> notify : 'subject -> 'event -> unit
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> <span class="ocamlkeyword">virtual</span> ['subject, 'event] observer :
<span class="ocamlkeyword">object</span> <span class="ocamlkeyword">method</span> <span class="ocamlkeyword">virtual</span> notify : 'subject -> 'event -> unit <span class="ocamlkeyword">end</span></div></div>
</div><p>
The class <span class="c003">subject</span> remembers a list of observers in an instance variable,
and has a distinguished method <span class="c003">notify_observers</span> to broadcast the message
<span class="c003">notify</span> to all observers with a particular event <span class="c003">e</span>.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['observer, 'event] subject =
<span class="ocamlkeyword">object</span> (self)
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> observers = ([]:'observer list)
<span class="ocamlkeyword">method</span> add_observer obs = observers <- (obs :: observers)
<span class="ocamlkeyword">method</span> notify_observers (e : 'event) =
List.iter (<span class="ocamlkeyword">fun</span> x -> x#notify self e) observers
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a, 'event] subject :
<span class="ocamlkeyword">object</span> ('b)
<span class="ocamlkeyword">constraint</span> 'a = < notify : 'b -> 'event -> unit; .. >
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> observers : 'a list
<span class="ocamlkeyword">method</span> add_observer : 'a -> unit
<span class="ocamlkeyword">method</span> notify_observers : 'event -> unit
<span class="ocamlkeyword">end</span></div></div>
</div><p>
The difficulty usually lies in defining instances of the pattern above
by inheritance. This can be done in a natural and obvious manner in
OCaml, as shown on the following example manipulating windows.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">type</span> event = Raise | Resize | Move;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">type</span> event = Raise | Resize | Move</div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> string_of_event = <span class="ocamlkeyword">function</span>
Raise -> <span class="ocamlstring">"Raise"</span> | Resize -> <span class="ocamlstring">"Resize"</span> | Move -> <span class="ocamlstring">"Move"</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> string_of_event : event -> string = <<span class="ocamlkeyword">fun</span>></div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> count = <span class="ocamlkeyword">ref</span> 0;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> count : int <span class="ocamlkeyword">ref</span> = {contents = 0}</div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['observer] window_subject =
<span class="ocamlkeyword">let</span> id = count := succ !count; !count <span class="ocamlkeyword">in</span>
<span class="ocamlkeyword">object</span> (self)
<span class="ocamlkeyword">inherit</span> ['observer, event] subject
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> position = 0
<span class="ocamlkeyword">method</span> identity = id
<span class="ocamlkeyword">method</span> move x = position <- position + x; self#notify_observers Move
<span class="ocamlkeyword">method</span> draw = Printf.printf <span class="ocamlstring">"{Position = %d}\n"</span> position;
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a] window_subject :
<span class="ocamlkeyword">object</span> ('b)
<span class="ocamlkeyword">constraint</span> 'a = < notify : 'b -> event -> unit; .. >
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> observers : 'a list
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> position : int
<span class="ocamlkeyword">method</span> add_observer : 'a -> unit
<span class="ocamlkeyword">method</span> draw : unit
<span class="ocamlkeyword">method</span> identity : int
<span class="ocamlkeyword">method</span> move : int -> unit
<span class="ocamlkeyword">method</span> notify_observers : event -> unit
<span class="ocamlkeyword">end</span></div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['subject] window_observer =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> ['subject, event] observer
<span class="ocamlkeyword">method</span> notify s e = s#draw
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a] window_observer :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">constraint</span> 'a = < draw : unit; .. >
<span class="ocamlkeyword">method</span> notify : 'a -> event -> unit
<span class="ocamlkeyword">end</span></div></div>
</div><p>
As can be expected, the type of <span class="c003">window</span> is recursive.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> window = <span class="ocamlkeyword">new</span> window_subject;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> window : < notify : 'a -> event -> unit; _.. > window_subject <span class="ocamlkeyword">as</span> 'a =
<obj></div></div>
</div><p>
However, the two classes of <span class="c003">window_subject</span> and <span class="c003">window_observer</span> are not
mutually recursive.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> window_observer = <span class="ocamlkeyword">new</span> window_observer;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> window_observer : < draw : unit; _.. > window_observer = <obj></div></div>
<div class="ocaml">
<div class="pre caml-input"> window#add_observer window_observer;;</div>
<div class="pre caml-output ok">- : unit = ()</div></div>
<div class="ocaml">
<div class="pre caml-input"> window#move 1;;</div>
<div class="pre caml-output ok">{Position = 1}
- : unit = ()</div></div>
</div><p>Classes <span class="c003">window_observer</span> and <span class="c003">window_subject</span> can still be extended by
inheritance. For instance, one may enrich the <span class="c003">subject</span> with new
behaviors and refine the behavior of the observer.
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['observer] richer_window_subject =
<span class="ocamlkeyword">object</span> (self)
<span class="ocamlkeyword">inherit</span> ['observer] window_subject
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> size = 1
<span class="ocamlkeyword">method</span> resize x = size <- size + x; self#notify_observers Resize
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> top = <span class="ocamlkeyword">false</span>
<span class="ocamlkeyword">method</span> raise = top <- <span class="ocamlkeyword">true</span>; self#notify_observers Raise
<span class="ocamlkeyword">method</span> draw = Printf.printf <span class="ocamlstring">"{Position = %d; Size = %d}\n"</span> position size;
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a] richer_window_subject :
<span class="ocamlkeyword">object</span> ('b)
<span class="ocamlkeyword">constraint</span> 'a = < notify : 'b -> event -> unit; .. >
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> observers : 'a list
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> position : int
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> size : int
<span class="ocamlkeyword">val</span> <span class="ocamlkeyword">mutable</span> top : bool
<span class="ocamlkeyword">method</span> add_observer : 'a -> unit
<span class="ocamlkeyword">method</span> draw : unit
<span class="ocamlkeyword">method</span> identity : int
<span class="ocamlkeyword">method</span> move : int -> unit
<span class="ocamlkeyword">method</span> notify_observers : event -> unit
<span class="ocamlkeyword">method</span> raise : unit
<span class="ocamlkeyword">method</span> resize : int -> unit
<span class="ocamlkeyword">end</span></div></div>
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['subject] richer_window_observer =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> ['subject] window_observer <span class="ocamlkeyword">as</span> super
<span class="ocamlkeyword">method</span> notify s e = <span class="ocamlkeyword">if</span> e <> Raise <span class="ocamlkeyword">then</span> s#raise; super#notify s e
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a] richer_window_observer :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">constraint</span> 'a = < draw : unit; raise : unit; .. >
<span class="ocamlkeyword">method</span> notify : 'a -> event -> unit
<span class="ocamlkeyword">end</span></div></div>
</div><p>
We can also create a different kind of observer:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">class</span> ['subject] trace_observer =
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">inherit</span> ['subject, event] observer
<span class="ocamlkeyword">method</span> notify s e =
Printf.printf
<span class="ocamlstring">"<Window %d <== %s>\n"</span> s#identity (string_of_event e)
<span class="ocamlkeyword">end</span>;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">class</span> ['a] trace_observer :
<span class="ocamlkeyword">object</span>
<span class="ocamlkeyword">constraint</span> 'a = < identity : int; .. >
<span class="ocamlkeyword">method</span> notify : 'a -> event -> unit
<span class="ocamlkeyword">end</span></div></div>
</div><p>
and attach several observers to the same object:
</p><div class="caml-example toplevel">
<div class="ocaml">
<div class="pre caml-input"> <span class="ocamlkeyword">let</span> window = <span class="ocamlkeyword">new</span> richer_window_subject;;</div>
<div class="pre caml-output ok"><span class="ocamlkeyword">val</span> window :
< notify : 'a -> event -> unit; _.. > richer_window_subject <span class="ocamlkeyword">as</span> 'a = <obj></div></div>
<div class="ocaml">
<div class="pre caml-input"> window#add_observer (<span class="ocamlkeyword">new</span> richer_window_observer);;</div>
<div class="pre caml-output ok">- : unit = ()</div></div>
<div class="ocaml">
<div class="pre caml-input"> window#add_observer (<span class="ocamlkeyword">new</span> trace_observer);;</div>
<div class="pre caml-output ok">- : unit = ()</div></div>
<div class="ocaml">
<div class="pre caml-input"> window#move 1; window#resize 2;;</div>
<div class="pre caml-output ok"><Window 1 <== Move>
<Window 1 <== Raise>
{Position = 1; Size = 1}
{Position = 1; Size = 1}
<Window 1 <== Resize>
<Window 1 <== Raise>
{Position = 1; Size = 3}
{Position = 1; Size = 3}
- : unit = ()</div></div>
</div>
<hr>
<a href="polymorphism.html"><img src="previous_motif.svg" alt="Previous"></a>
<a href="index.html"><img src="contents_motif.svg" alt="Up"></a>
<a href="language.html"><img src="next_motif.svg" alt="Next"></a>
</body>
</html>
|