根据刘伟的文章(java),转换成ios的。
http://blog.csdn.net/lovelion/article/details/9300657
接口抽象类:chart
chart.h
@interface Chart : NSObject
-(void)display;
@end
chart.m
#import "Chart.h"
@implementation Chart
-(void)display
{
NSLog(@"display chart");
}
@end
具体类:
HistogramChart.h#import <Foundation/Foundation.h>
#import "Chart.h"
@interface HistogramChart :Chart
-(HistogramChart *)initHistogramChart;
@end
HistogramChart.m
#import "HistogramChart.h"
@implementation HistogramChart
-(HistogramChart *)initHistogramChart
{
HistogramChart *histogramChart;
if (self = [super init]) {
NSLog(@"Creat HistogramChart");
histogramChart = [[HistogramChart alloc] init];
}
return histogramChart;
}
-(void)display
{
NSLog(@"display HistogramChart");
}
@end
PieChart.h
#import <Foundation/Foundation.h>
#import "Chart.h"
@interface PieChart : Chart
-(PieChart *)initPieChart;
@end
PieChart.m
#import "PieChart.h"
@implementation PieChart
-(PieChart *)initPieChart
{
PieChart *pie;
if (self = [super init]) {
NSLog(@"Creat PieChart");
pie = [[PieChart alloc] init];
}
return pie;
}
-(void)display
{
NSLog(@"display PieChart");
}
@end
LineChart.h
#import <Foundation/Foundation.h>
#import "Chart.h"
@interface LineChart : Chart
-(LineChart *)initLineChart;
@end
LineChart.m
#import "LineChart.h"
@implementation LineChart
-(LineChart *)initLineChart
{
LineChart *line;
if (self = [super init]) {
line = [[LineChart alloc] init];
NSLog(@"Creat LineChart");
}
return line;
}
-(void)display
{
NSLog(@"display LineChart");
}
@end
工厂类:
ChartFactory.h
#import <Foundation/Foundation.h>
#import "HistogramChart.h"
#import "PieChart.h"
#import "LineChart.h"
#import "Chart.h"
@interface ChartFactory : NSObject
+(Chart *)getChart:(NSString *)type;
@end
ChartFactory.m
#import "ChartFactory.h"
@implementation ChartFactory
+(Chart *)getChart:(NSString *)type
{
Chart *chart;
if ([type isEqualToString:@"HistogramChart"])
{
chart = [[HistogramChart alloc] initHistogramChart];
NSLog(@"init HistogramChart");
}
else if ([type isEqualToString:@"PieChart"])
{
chart = [[PieChart alloc] initPieChart];
NSLog(@"init PieChart");
}
else if ([type isEqualToString:@"LineChart"])
{
chart = [[LineChart alloc] initLineChart];
NSLog(@"init LineChart");
}
else
{
NSLog(@"don't have it is Chart");
}
return chart;
}
@end
最后是main方法:
#import <Foundation/Foundation.h>
#import "Chart.h"
#import "ChartFactory.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Chart *chart = [ChartFactory getChart:@"HistogramChart"];
[chart display];
}
return 0;
}
这就应该是ios版的工厂方法了吧。。。。不是很确定。