1. Trang chủ
  2. » Kỹ Thuật - Công Nghệ

CRC.Press A Guide to MATLAB Object Oriented Programming May.2007 Episode 2 Part 3 doc

20 196 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề A Guide to MATLAB Object-Oriented Programming
Trường học University of California, Berkeley
Chuyên ngành Computer Science
Thể loại Essay
Năm xuất bản 2007
Thành phố Berkeley
Định dạng
Số trang 20
Dung lượng 890,29 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Helper functions return values for these two variables, but we never know in advance whether a direct-link public variable or a non-direct-direct-link variable is being accessed.. Allowi

Trang 1

28 case 'Color'

nargout

varargin{:}]);

52

54 if ~found && called_by_name

67

Trang 2

72 else

75

81

varargin{:});

sub-indexing

105

107 if ~found

112

114 if length(varargout) > 1 & nargout <= 1

varargout)])

Trang 3

The first changes occur in lines 3 and 4 The local variables do_sub_indexing and

do_assignin guard code blocks near the end of this now standard version of get Helper functions return values for these two variables, but we never know in advance whether a direct-link public variable or a non-direct-direct-link variable is being accessed Lines 3 and 4 assign initial values compatible with direct-link access During non-direct-link access, the helper function assigns values to these variables

125

objects');

'set'}))

139

143 if length(index) > 0

146

array_reference_error(index(1).type);

Trang 4

The next change brings us into the public member variable section The case for ‘Color’, lines 28–36, uses a helper function As before, line 28 identifies the ‘Color’ case, and when the object is empty, line 30 returns an empty varargout When the object is not empty, line 32 prepares for the helper call by preallocating varargout Lines 34–35 call the helper There are three input arguments and three plus length(varargout) outputs

The first input, ‘get’, tells the helper to perform an access operation The second input,

this, is the source of the access The third input is a concatenation of index(2:end) and

varargin{:} The values in index and varargin depend on the path leading up to the helper call If the path began with dot-reference syntax, index(2:end) will contain additional indices converted from operator notation and varargin will be empty If the path began with a call to

get, index(2:end) will be empty but varargin might include an additional substruct

index The concatenation assembles the entire index and passes it into the helper

One important thing to notice is the fact that there is no limit imposed on the length of the index passed into the helper Ordinarily MATLAB places limits on indexing into nonscalar variables

In most situations, the group-of-eight implementation also places limits on indexing The length

of the index passed into the helper is an exception because the helper is responsible for these decisions When the helper accepts this responsibility it returns a value of false in

do_sub_indexing

The helper returns values for do_sub_indexing, do_assignin, this, and varar-gout Allowing the helper to index into the dot-referenced value and return a do_sub_indexing

value of false means that values returned from the helper might be fully indexed This has implications for subsref because, currently, subsref will incorrectly reindex the values To fix this problem, indexing code is moved out of subsref and into lines 140–151 The code previously shown in Code Listing 98 will no longer exist in the standard version of subsref Instead, all standard versions of get will include the ability to perform deeper indexing It should come as no surprise that the do_sub_indexing flag guards this ability

The helper also returns a value for do_assignin Do_assignin is used as a guard value for lines 127–138 These lines implement some special syntax that will be described in Part 3 Until we take up that discussion, the value returned by the helper will always be false That way, until we discuss the pros and cons of returning a true value, we will skip over 127–138 You might also notice other do_assignin-related additions These additions are also discussed

in Part 3

The final addition occurs on line 87 inside the parent-forwarding section When the get forward

in line 85 executes without error, line 86 sets found equal to true and line 87 sets

do_sub_indexing to false Now that we have moved the indexing code into get, the parent’s version will have already performed any necessary indexing and we don’t want to reindex the values Of course, this also means that all of our classes need to be updated with the new group-of-eight functions described in this chapter

16.1.2.3 Final Template for set.m

Case code for set is shown in Code Listing 101

Code Listing 101, Final Version of set.m Implemented for cLineStyle

2

3 do_assignin = false; % special variable, see book section 3 4

5 if nargin < 3 % one or two arguments, display info and return

Trang 5

6 possible = fieldnames(this, '-possible');

26

28

33

varargin{:});

.type);

Trang 6

51 error(err_id, err_msg);

59

61 if ~found && called_by_name

76

84

varargin{:});

Trang 7

The first change to set occurs in line 3 The logical variable do_assignin guards entry into the block of code added in lines 110–122 Behavior related to do_assignin will be described

in Part 3 Until then, do_assignin should be false and line 3 assigns false as the initial value

The next change brings us into the public member variable section The case for ‘Color’, lines 37–39, uses a helper function Line 37 identifies the ‘Color’ case, and lines 38–39 call the helper This time the first argument is ‘set’ because we want to execute the mutator The remaining three arguments are the object, the additional indices, and the assignment values The helper returns values for do_sub_indexing, do_assignin, and the mutated object In this case, do_sub_indexing is a dummy variable because it is never used by set

The case for ‘LineWidth’ is interesting because get uses direct-link code but set uses a helper This is typical because the standard organization moves input-value-checking code into the helper The mutator needs to check the input values, but the accessor does not Thus, the mutator uses a helper but the accessor does not Finally, the case for LineHandle uses the standard direct-link syntax

104

105 if ~found

110

111 if do_assignin % set used in special way, see book section 3

non-indexed object');

'get' 'set'}))

124

Trang 8

16.1.2.4 Color Helper Function

Code for one combined accessor–mutator helper function is shown in Code Listing 102 This particular helper is used for the public member variable color Code in the listing should look familiar because most of the lines came directly from member functions in Chapter 15 Of course, the organization is different and there is a lot going on in this function

Code Listing 102, Final Version of cLineStyle’s Color_helper.m

3

5

mat2cell 11

13 do_sub_indexing = false; % mutator must do deeper indexing

varargin{:});

type);

28

'Color'));

34

Trang 9

First notice the file is separated into two sections: accessor (lines 3–10) and mutator (lines 12–37) This is not necessarily required, but it is a convenient organization Both sections assign values to do_sub_indexing, do_assignin, and varargout The accessor code can allow

get to finish deeper indexing by setting do_sub_indexing equal to true That is what this helper does on line 7 The accessor code can also elect to perform deeper indexing by setting

do_sub_indexing equal to false The mutator code must always perform deeper indexing and will always set do_sub_indexing equal to false

The accessor code then converts private HSV values into RGB values on line 9 To populate the varargout cell array, line 10 converts the RGB array values into a cell array The mutator code doesn’t return values via varargout, so it sets varargout to empty in line 15

Instead of using varargout, mutator code performs the mutation in place and returns the mutated object When the variable name is the only index, line 17 copies input RGB values into

a temporary variable When there are additional indices, line 19 checks the size of the object array

If the array is scalar, line 20 uses subsasgn to assign the subset If the array is nonscalar, lines 22–23 throw an error by calling array_reference_error

After populating the rgb temporary variable, line 26 converts the RGB values into HSV values and stores the HSV values in a cell array Line 27 then deals the cell values into the correct locations Finally, lines 29–33 loop over all the objects in the array and set their line colors to the newly assigned values Just like before, using the handle-graphics set silently does nothing when the handle is empty

16.1.2.5 The Other Classes and Member Functions

Before cLineStyle can be used in our current collection of classes, we need to code

LineWidth_helper The implementation follows the same strategy used for Color_helper The code is included in the Chapter 16 @cLineStyle/private directory The mutator section includes index checking, value checking, and input size checking identical to Chapter 15’s set case While not technically required, we should also be able to convert member functions for

cShape, cStar, and cDiamond into this chapter’s newly established, group-of-eight format The old class organization will work with the new version of cLineStyle because its public interface didn’t change The problem with keeping the old class organization is one of consistency

A collection of classes is much easier to maintain if they all consistently conform to the same internal strategy Affected group-of-eight member functions are get, set, subsref, and

subsasgn

The new organization also uses helper functions for non-direct-link public variables The previous implementations for cShape, cStar, and cDiamond were also reorganized to use helpers Implementations of the various helper functions follow the same strategy laid out in this chapter The newly organized class files can be found in the chapter_16 directory You should look at these files and pay close attention to the helper functions in the private directories

16.2 TEST DRIVE

The code in this chapter represents reorganization with no new functionality All of the commands from previous chapters should still work the same as they did before We need to rerun some of our test commands to make sure our classes still behave the same Some of the Chapter 15

which]);

Trang 10

commands for cStar objects are repeated in Code Listing 103 The commands confirm that the helper-function interface is working correctly across our parent–child and primary-secondary hier-archies The figure that results from the command in line 6 is shown in Figure 16.1

16.3 SUMMARY

The focus of this chapter was the organization of get and set By changing the organization, we improved the modularity of the standard group of eight To do this we considered two situations: direct-link variables and variables that use a helper function Direct-link variables are easy to access and mutate because there is no data conversion or input checking The code to access and mutate these variables is short and essentially the same every time Public variables that use a helper include those that convert data from one representation to another and those that perform any sort

if input check during mutation

FIGURE 16.1 cStar graphic after implementing helper-function syntax.

Code Listing 103, Chapter 16 Test Drive Command Listing: The cStar Interface

1 >> cd '/oop_guide/chapter_16'

2 >> clear classes; fclose all; close all force; diary off;

3 >> star = [cStar cStar];

4 >> star(2).ColorRgb = [1;0;0];

5 >> star(1) = 1.5 * star(1);

6 >> star = draw(star);

7 >> star(1).Title = 'Shooting Star';

8 >> star(1).LineWeight = 'bold';

9 >> star(1)

2

1

0

–1

–2

1 0

Shooting Star

–1

Trang 11

Moving accessor and mutator code outside of get and set also has another benefit It allows computer-aided-software-engineering (CASE) tools to manage the addition and removal of private, public, and concealed variables Without helper functions and their standard interface, every time

a class changes, a lot of hand tailoring is required The next chapter introduces a very capable CASE tool that exploits all of the group of eight’s organizational elements

16.4 INDEPENDENT INVESTIGATIONS

1 Repeat the same commands using a cDiamond object instead of a cStar object

2 Experiment with the implementation by accessing and mutating elements using multiple indexing levels

Trang 12

With sixteen chapters under your belt, you can now create sophisticated, robust MATLAB classes

on your own During the first few implementations, it is easy to stay motivated because there are many new twists and turns After the first few, however, the repetitive syntax can quickly become monotonous and time-consuming At some point, you need to shift back into a product focus but the implementation mechanics are too tedious to allow your attention to waver Once you shift from “How do I implement objects?” back to “How do I use objects to implement products?” you are likely to find yourself wishing for some sort of class-generation tool Standard, repetitive tasks like building the group-of-eight functions are ideally suited for automation Of course, this did not happen by accident Modularity along with a constant drive to isolate class-dependent code into a small subset of functions makes automation possible

This chapter introduces an automated code-generation tool that simplifies group-of-eight devel-opment for MATLAB classes Using the tool, you can define a collection of public and private member variables along with an associated collection of public and private member functions The tool will use these to generate fully functional class code that follows the guidelines developed in the previous sixteen chapters All of the various bells and whistles are included The tool will even give you a head start on class tailoring by generating a function template for public functions and helpers The template includes the function definition along with reasonably complete header comments This is convenient because it gives variable names and comment headers a consistent form with shared comments across all members of the class

The automation tool is called class_wizard.m The Class Wizard tool uses a graphical interface entirely developed using MATLAB’s standard development tools Dialog screens and callback functions were developed using Guide* and MATLAB 7.0 In addition, all of the code in

class_wizard.m is native MATLAB The main Class Wizard function along with other required functions can be found on the source disk in /oop_guide/utility/wizard_gui I recom-mend that you add this directory to the MATLAB path or copy all the files to a directory already

on the path If you don’t want to put the wizard on your path, you can cd into its directory to run it The first time you run Class Wizard, you will immediately recognize its organization Data-entry areas on the main dialog correspond to specific areas in the group of eight There are Data-entry areas for parent classes, private variables, concealed variables, public variables, and constructors The more… button opens another dialog where details for public functions and some other advanced elements can be entered We will discuss these advanced elements in Part 3

In this chapter, you will find a concise introduction to Class Wizard The introduction describes the various data-entry screens, field formats, file operations, and class generation The descriptions assume that you are already familiar with the organization and implementation strategy behind the group of eight and their helpers For example, descriptions in this chapter assume that you are familiar with private, concealed, and public variables and understand how they relate to one another This chapter describes data entry for the code-generation tool, but in reality, the full documentation for Class Wizard is the topic of this book

* Guide is a standard MATLAB utility that can be used to efficiently create cross-platform graphical user interfaces MATLAB version 7.0 added button groups to the standard set of graphical components, and Class Wizard uses button groups For this reason Class Wizard will not run properly under versions of MATLAB below 7.0 There were also some changes to the object model; however, Class Wizard produces class code that is backward compatible with MATLAB version 6.5.

Ngày đăng: 05/08/2014, 21:21