根据方法输入更改对象初始化器/构造函数 [英] Changing Object initializer/constructor depending on method input

查看:197
本文介绍了根据方法输入更改对象初始化器/构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图避免使用重复的代码。目前我有几个包含字符串的列表;一个列表称为图像和其他视频等。这些列表包含内容的属性,并且它们在链接列表中,因为该信息是从文本文件读取的。

So I am trying to avoid using duplicate code. At the moment I have several lists which contain Strings; one list is called "images" and the other "videos" etc. These lists contain the properties of the content and they are in a linked list because that information was read from a text file.

我试图通过这些列表,并创建图像/视频对象放置在另一个对象(后来)。

I am trying to go through these lists and create image/video objects to place in another object (later on).

目前我有一个方法

private void loadContent(List<String> contentType)

它如何根据名称更改对象声明等的通过的列表。例如:
如果我调用的方法与图像列表:

inside of it how do I change the object declarations etc depending on the name of the list that was passed through. For example: If I call the method with the image list:

loadContent(images)

我想要该函数创建图像对象:

I want the function to create image objects:

Image media = new Image(title, visibility);

如果我通过视频列表:

loadContent(videos)

对象:

Video media = new Video(title, visibility);

对不起,如果这措辞不好,我发现很难阐明这个问题。我也理解了多态的概念;我只是看不到内容对象可以做这个工作(读取字符串等)根据列表的内容创建对象。

Sorry if this is worded badly, I find it hard to articulate this question. I also understand the the concept of polymorphism; I just don't see it viable for the content object to do this job (of reading the string etc) as the object is created depending the contents of the list.

推荐答案

你提出了多态性的主题。这种情况将是一个很好的候选人,以证明你的理解如何工作。您可以创建一个名为Media的抽象类,并定义一个名为Render()的方法。然后将Media类扩展到两个子类,ImageMedia和VideoMedia。当每个子类扩展类Media时,他们应该用自己的如何渲染内容的实现来重写方法Render()。最后你可以只有一个类型为Media的列表,如下:List< Media>并在它上面调用Render()方法时遍历它。通过这种方式,您可以强制实施多态行为并极大地简化您的代码。

You brought up the subject of Polymorphism. This scenario would be a good candidate to demonstrate your understanding of how it works. You could create an abstract class named Media and have one method defined named Render(). Then extend the Media class to two subclasses, ImageMedia and VideoMedia. Where each subclass extends class Media, they should override the method Render() with their own implementation of how to render the content. In the end you can just have a List of type Media like this: List<Media> and iterate over it while calling the Render() method on each. In this way you impose polymorphic behaviour and greatly simplify your code.

这篇关于根据方法输入更改对象初始化器/构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆